问题
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