Add Class To Closest Element [duplicate]

两盒软妹~` 提交于 2020-01-16 17:59:35

问题


I'm trying to add a class to dynamically created objects, but there is something that is going wrong here. And I can't get it to work!

Any ideas?

<span class="status"><div class="like_button"></div></span>

 <script>  
   $(this).closest('span').find('.like_button').addClass('liked')
</script>

UPDATE:

Thing is I am having a Facebook like button (created with the API not the regular one) inside each of the elements, and needs to check its status before I can add class "liked" or "unliked". So all the div's with class "item" is created in a PHP loop. And also I understand its not good to run the script several times in a loop. But I need to get further in the testings here :)

<div class="item">
 <span class="status"><div class="like_button"></div></span>
 <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

 <div class="item">
 <span class="status"><div class="like_button"></div></span>
 <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

 <div class="item">

 <span class="status"><div class="like_button"></div></span>
  <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

 <div class="item">
 <span class="status"><div class="like_button"></div></span>
  <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

回答1:


When the code in the script tag will be running, the <span> will be the last loaded tag.

That beign said, you can do this :

$('span:last').find('.like_button').addClass('liked')

Fiddle : http://jsfiddle.net/NRUuV/




回答2:


Assuming $(this) is span: $(this).next().addClass('liked')



来源:https://stackoverflow.com/questions/16943671/add-class-to-closest-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!