【问题标题】:Get variable from current div for getJSON statement从当前 div 获取变量以获取 getJSON 语句
【发布时间】:2013-07-03 09:15:20
【问题描述】:

我有一个包含多个具有相同类的 div 的页面。我想打开一个模态窗口,然后用 JSON/动态内容填充模态。为此,我需要获取正确的 url 以在 getJson 语句中使用。所以我有一个包含多个产品的页面,如下所示:

HTML

<div class="product" style="opacity: 1;">
   <a title="product" **href="url-to-product.com"**>..................</a>
   <h3><a href="url-to-product.com">Blabla</a></h3>
   <div class="button opener">...</div>
</div>
<div class="product" style="opacity: 1;">
   <a title="product" **href="other-url-to-product.com"**>..................</a>
   <h3><a href="other-url-to-product.com">Blabla</a></h3>
   <div class="button opener">...</div>
</div> 

当我单击按钮时,会弹出一个模式。现在我想用内容填充那个模式。因此我需要 ** ** 之间的 href 值。只有一个来自当前点击的产品offcourse。所以我有的是这样的:

JQUERY

 $(".opener").live("click", function(event) {
     event.preventDefault();
          $.get($(this).attr('href'), function(data, status) {
            $("#dialog").dialog("open");

            var url = $(this).find('h3 > a').attr('href'); 

//这不起作用,需要像上面提到的那样来自href的值

            $.getJSON(url, function(data) {                          
              $.each(data.product, function(index, product){ 
              ......... etc .......

【问题讨论】:

    标签: jquery json modal-dialog


    【解决方案1】:

    您可以使用siblings() 选择器来获取 div 元素的兄弟。

    var url = $(this).siblings('a').attr('href');
    

    var url = $(this).siblings('h3').children('a').attr('href');
    

    【讨论】:

      【解决方案2】:

      您正在尝试使用来自div.openerhref 属性而不是来自.product &gt; a 的数据。

      试试这个代码:

      $(".opener").live("click", function(event) {
          event.preventDefault();
          var url = $(this).parents('.product').find(' > a').attr('href');
      
          // do whatever you need using the url you wanted to get
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-29
        • 2020-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多