how do i change id of a element every time it is clicked with jquery -


how change id of element every time clicked jquery? have code works fine on first click, when clicked again, still calls old id.

$("#like<? echo $msgid;?>").click(function(){                                                      $.post("like.php?status_id=<? echo $msgid;?>", $(this).serialize());         settimeout(function() {         $("#likediv<? echo $msgid;?>").load('like-count.php?status_id=<? echo $msgid;?>');         $("#like<? echo $msgid;?>").attr("id","unlike<? echo $msgid;?>").text("unlike");         },500);         }); $("#unlike<? echo $msgid;?>").click(function(){                                              $.post("unlike.php?status_id=<? echo $msgid;?>", $(this).serialize());         settimeout(function() {         $("#likediv<? echo $msgid;?>").load('like-count.php?status_id=<? echo $msgid;?>');         $("#unlike<? echo $msgid;?>").attr("id","like<? echo $msgid;?>").text("like");         },500);         }); 

the problem isn't id isn't changing, you've bound click handlers already. in general sense, if this:

$("#someid").click(... 

it binds click handler element has id at moment, , click handler continues bound element if change id later.

in case start out trying bind click handler 2 elements, 1 id starting #like , other id starting #unlike, 1 such element exists , 1 handler bound.

you need either change use delegated event handlers, bound parent element (or document) , on click test whether clicked item matches selector, or combine 2 click handlers 1 handler tests current state of element:

$("#like<? echo $msgid;?>").click(function () {     var islike = $(this).text() === "like",         url = islike ? "like.php" : "unlike.php";     $.post(url + "?status_id=<? echo $msgid;?>", $(this).serialize());     settimeout(function () {         $("#likediv<? echo $msgid;?>").load('like-count.php?status_id=<? echo $msgid;?>');         $("#like<? echo $msgid;?>").text(islike ? "unlike" : "like");     }, 500); }); 

you didn't show html, i'm assuming #like... element not inside #likediv... element (because if reloaded .load() , remove click handler).

i can add code show how 2 delegated handlers instead, way of thinking makes more sense combine handlers shown, because same element being clicked , displayed text needs change.

(also, aside, why using settimeout()? wouldn't make sense put in callback function third argument $.post()?)


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -