1

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?

2 Answers 2

3

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');
});
Sign up to request clarification or add additional context in comments.

7 Comments

This works nicely, just need to get it to go up back to the li above the link to remove the "notlike" and change it to a different one. But only for that one link..
you can use .closest('li') to get the first li up. So $(this).closest('li').removeClass('notlike')
Yup perfect, I was trying prevAll() but this works. Thank You
prevAll() is for siblings not parents
$(this).addClass('y').siblings().removeClass('x')
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.