【问题标题】:jQuery find text and write into another tag attribute with each functionjQuery 使用每个函数查找文本并写入另一个标签属性
【发布时间】:2016-09-14 11:29:41
【问题描述】:

.. 你好

我尝试从我的figcaption-Element 中获取文本并插入到相应的a-Tag -> (data-title)

目前我找到了 figcaption 并将其写入变量“desc”。但是每个 figcaption 都应该从链接插入到data-title。现在只有最后一个desc 会被写入data-title

这是fiddle 和我的jQuery-code:

jQuery('figure').find('figcaption').each(function (index) {
    var desc = $(this).text();
    //var desc = jQuery('figcaption').text();
    console.log(index + desc);
    jQuery('.lightbox2').attr('data-title', ''+ desc +'');
});

感谢您的帮助。

【问题讨论】:

  • 请发布代码而不是代码的图像

标签: javascript jquery function find each


【解决方案1】:

你可以只使用.text()的回调

$('figure figcaption').text(function(el, txt) {
    $(el).prev('a.lightbox2').attr('data-title', txt);
});

attr() 也一样

$('a.lightbox2').attr('data-title', function() {
    return $(this).next('figcaption').text();
});

但是,只要您在小提琴中包含 jQuery,您的代码就可以正常工作 -> https://jsfiddle.net/adeneo/60mm991f/1/

【讨论】:

  • 感谢您的帮助。我对我的attr() 使用相同的。
【解决方案2】:

您可以使用.attr(attributeName, function)

$('a.lightbox2').attr('data-title', function(ele){
    return $(ele).closest('figure').find('figcaption').text();
})

您的代码只需稍作修改即可使用Updated Fiddle

jQuery(this).prev('.lightbox2').attr('data-title', '' + desc + '');

而不是

jQuery('.lightbox2').attr('data-title', '' + desc + '');

【讨论】:

  • 感谢您的帮助..您的解决方案也可以正常工作。
猜你喜欢
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
相关资源
最近更新 更多