i have this jQuery file, but the vote_up click handler keeps conflicting with the vote_down click handler, when i click the vote_down element it changes the vote_up element:
jQuery script:
$(document).ready(function () {
$("a.vote_up").click(function () {
//get the id
var the_id = this.id.split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
$("span.vote_count#" + the_id).html(msg).fadeIn();
$("#" + the_id + " img").attr("src", "img/uparrowActive.png");
}
});
});
});
$(document).ready(function () {
// the vote down function
$("a.vote_down").click(function () {
//get the id
var vote_id = this.id.split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_down&id=" + vote_id,
url: "ajax/votes.php",
success: function (msg) {
$("span.vote_count#" + vote_id).html(msg).fadeIn();
$("#" + vote_id + " img").attr("src", "img/downarrowActive.png");
}
});
});
});
html:
<a href='#' class='vote_up' id="id_23"><img src="img/uparrow.png" /></a>
<a href='#' class='vote_down' id="id_23"><img src="img/downarrow.png" /></a>
the jQuery and ajax request is wokring fine, but the change of src is the problem, because when i click vote down, it changes the vote_up image!!
If you’re looking for some sort of strategy for focusing events to a repeating piece of data, utilizing IDs with the number appended to reference the various elements may work, but may not be the best approach.
I assume each repeating item has its own container that repeats. You may be better off placing a unique ID on that container, and finding the elements from there.
Take this for example:
You could use
.delegate()to place click handlers on the#outerContainerthat fire when you click the appropriate up/down elements.Something like:
So the ID with the number you need is on each
.someContainer. You traverse up to that container to get the ID, and do your.split().pop().Then in the AJAX request, I set the
context:property for$.ajax()so thatthiswill still refer to the element that was clicked in your callback.Inside the callback, you find the
.siblings()that have the class.vote_count, and set its.html()content.Finally you use
.children()to get theimgelement, and set itssrcattribute.This should give the general idea. You’ll need to adjust for your HTML.