【问题标题】:Get text inside a div and place it as a value of another attribute获取 div 内的文本并将其作为另一个属性的值
【发布时间】:2013-03-27 16:00:12
【问题描述】:

我需要获取每个“dd”中的文本并将其作为相关“a.myClass”的数据描述属性的值。如果仅在存在 'gallery-caption' 时才创建 data-description 属性,那将是完美的。

HTML

<dl>
    <dt>
       <a class="myClass"></a>
    </dt>
    <dd class="gallery-caption">This is my caption</dd>
</dl>

当前的 JS(非工作)

$(".myClass").each(function(){

     var Caption = $(this).find('dd.gallery-caption').text();

     $(this).attr('data-description', Caption );

});

感谢您的帮助

最终工作解决方案

$(".myClass").each(function(){
     var Caption = $(this).parent().next('dd.gallery-caption').text();

     if (Caption && Caption !== ''){
         $(this).attr('data-description', Caption );
     }
});

【问题讨论】:

    标签: jquery attributes return-value


    【解决方案1】:

    你试过了吗

    $(this).parents("dl").find('dd.gallery-caption').text();
    

    http://docs.jquery.com/Traversing/parent

    【讨论】:

      【解决方案2】:

      为什么不在设置之前先检查一下?另外,可以使用.data("description")访问数据属性。

      另外,Caption 的选择器需要调整。

      试试这个:

      $(".myClass").each(function(){
      
           var Caption = $(this).parents("dl").find('dd.gallery-caption').text();
      
           if ($(this).data("data-description")) {
               $(this).data('description', Caption);
           }
      
      });
      

      演示:http://jsfiddle.net/taju4/

      【讨论】:

        【解决方案3】:

        你需要走得更远才能找到你的标题:

        $(".myClass").each(function(){
             var Caption = $(this).closest('dl').find('dd.gallery-caption').text();
             if (Caption && Caption !== ''){
                 $(this).attr('data-description', Caption );
             }
        });
        

        如果你在 DL 中有多个 DD/DT,那么你需要使用 next():

        var Caption = $(this).parent().next('dd.gallery-caption').text();
        

        【讨论】:

          【解决方案4】:

          看到dd.gallery-caption 不是.myClass 的孩子,所以试试.next()

          var Caption = $(this).parent().next('dd.gallery-caption').text();
          

          在这里,您遍历其父级,然后进入 dd 的下一级并找到 .gallery-caption 类并从中取出文本。

          虽然.siblings() 也可以实现同样的效果:

          var Caption = $(this).parent().siblings('dd.gallery-caption').text();
          

          在这里,您遍历其父级,然后在同一级别获取兄弟级并找到 .gallery-caption 类并从中取出文本。

          【讨论】:

          • 谢谢你,我可以用你的第一个解决方案正确地达到所需的内容。我将它与@Syon 提供的 if 语句结合起来,我将用最终解决方案更新我的问题。谢谢大家
          猜你喜欢
          • 2012-03-22
          • 2010-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-13
          • 2019-09-23
          • 2021-07-24
          相关资源
          最近更新 更多