jQuery-遍历一个父级并设置ID

jQuery - traversing up one parent and setting the ID

本文关键字:设置 ID 一个 遍历 jQuery-      更新时间:2023-09-26

我试图获取标签中的文本,并将其遍历到父级("li"),并在那里将其设置为ID。

它在每次迭代中都能正确地获得文本——然而,我在尝试将其设置为ID时遇到了问题。

<script> 
    $('.collapse li label').each(function() {
       var test = $(this, '.collapse li label').text();
       $(this, '.collapse li label').parent("li").attr("id", test );
    });
</script>

我也试过:

$('.collapse li').attr("id", test);

最后:

$( this ).parent('li').attr("id", test);

没有用。

请帮我理解看待这个问题的正确方式?

请看下面的图片,更好地展示它是什么;我正在努力实现:

访问$(this)对象时无需设置selectorcontext

 $( '.collapse li label' ).each(function() {
  var test = $(this).text();
  $(this).parent("li").attr("id", test );
 });

你的编码方式类似于

$(this).find('.collapse li label').text();

所以你找到了相同的元素。在你的情况下,这不会产生任何结果。