matthewb
matthewb

Reputation: 3476

jquery click with a loop?

I am trying to put a click function on a php loop.

But its doing part or all of the function on all the links..

I thought if used "this" it would solve it but it's not working..

Here is the jquery:

if ($('#like').hasClass('notlike')); {
    $('.likeon').click(function () {
        $('#like span.message', this).text('Yes I Like It');
    });
};

Here is the html:

<li id="like" class="notlike">
    <span>
        (3) Likes <br>
        <span class="message">
            <a href="javascript:;" class="likeon">Do You Like it?</a>
        </span>
    </span>
</li>

I am looping with php so the link appears 5 times. What Am I doing Wrong?

Upvotes: 1

Views: 291

Answers (2)

redsquare
redsquare

Reputation: 78667

I think you have a few issues.

Element ID's must be unique inside the dom. if you are looping over that html fragment then you will end up with multiple li tags with an id of like. You need to remove the id and use a class

e.g

<li id="like" class="notlike">
<span>(3) Likes <br>
   <span class="message">
   <a href="javascript:;" class="likeon">Do You Like it?</a>
   </span>
</span>
</li>

This will then allow you to write script as follows

$('li.someClass a.likeon').click ( function(){
   $(this).parent().text('Yes I Like It');
});

Also the context selector you were trying would never have worked as when you passed in the 'this' context it looks for elements below that match the selector. You did not have any child elements of the anchor with an id of like.

If you are changing these classes in script during the lifespan of the page then I would advise to use .live instead. This will mean that the event will fire even for anchors that do not currently have a class of likeon. If you later change the anchor to have that class it will still run

$('li.someClass a.likeon').live('click' , function(){
   $(this).parent().text('Yes I Like It');
});

Upvotes: 3

RaYell
RaYell

Reputation: 70414

Would be better to define click event handler like this

$('#like.notlike .likeon').click(function () {
    $(this).parent().text('Yes I Like It');
});

It's even shorter.

Upvotes: 1

Related Questions