将类添加到最近的元素

将类添加到最近的元素

问题描述:

我正在尝试向动态创建的对象添加一个类,但是这里有些地方出了问题.而且我无法正常工作!

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!

有什么想法吗?

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

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

更新:

问题是我在每个元素内都有一个类似Facebook的按钮(使用API​​创建的不是常规按钮),并且需要检查其状态,然后才能添加喜欢"或不喜欢"类.因此,所有具有"item"类的div都在PHP循环中创建.而且我也知道循环运行几次脚本不是很好.但是我需要在这里进行进一步的测试:)

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>

当script标记中的代码运行时,<span>将是最后加载的标记.

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')

小提琴: http://jsfiddle.net/NRUuV/