简体   繁体   English

jQuery-遍历一位父并设置ID

[英]jQuery - traversing up one parent and setting the ID

I'm trying to grab the text within a label - and traverse it up to the parent("li") and set it as an ID there. 我正在尝试获取标签内的文本-并将其遍历到parent(“ li”)并将其设置为ID。

It's getting the text correctly for each iterations - however I'm having issues trying to set it as an 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>

I've also tried: 我也尝试过:

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

And lastly: 最后:

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

To no avail. 无济于事。

Please help me understand the correct way of looking at this? 请帮助我了解正确的方法吗?

Please see the picture below to better show what it is; 请看下面的图片以更好地显示它是什么; i'm trying to achieve: 我正在努力实现:

There is no need to set the context of a selector while accessing $(this) object, 在访问$(this)对象时,无需设置selectorcontext

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

The way you coded is similar to, 您的编码方式类似于

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

So you are finding the same element. 因此,您正在找到相同的元素。 And that will not yield anything in your case. 在您的情况下,这不会产生任何效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM