tags:

views:

136

answers:

2

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?

+3  A: 

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');
});
redsquare
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..
matthewb
you can use .closest('li') to get the first li up. So$(this).closest('li').removeClass('notlike')
redsquare
Yup perfect, I was trying prevAll() but this works. Thank You
matthewb
prevAll() is for siblings not parents
redsquare
What do you think is the best way to remove a class from all other but the one you click on, this is not 100% related to this, but I am doing a function using what you mentioned, with 8 buttons, and I want to add a class on click then remove it from all other buttons not clicked?
matthewb
Nevermind, got it
matthewb
$(this).addClass('y').siblings().removeClass('x')
redsquare
You have a typo in second portion of the code (missing dot after $(this))
RaYell
I just wrote the remove class then the addclass in logic order, and it works..
matthewb
+1  A: 

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.

RaYell