Jquery - Only Change For Clicked Element, Not All With The Same Class
The code in the HTML/PHP section is pulled from a database in a while query, so the classes are repeated multiple times throughout the document. When I click on .up img, it changes
Solution 1:
You're on the right track with this
, and then you navigate to the sibling:
$(function() {
$('.up img').click( function(){
var $this = $(this);
var postDataUp = $this.attr('mod');
$.post('/votePost.php', {varUp: postDataUp}, function(o){
console.log(o);
$this.attr("src","img/up.png");
$this.closest('.up').nextAll('.down').first().find('img').attr("src","img/dw-g.png");
}, 'json');
});
});
...and similarly for the down
button. The long line for that would be prevAll
rather than nextAll
:
$this.closest('.down').prevAll('.up').first().find('img').attr("src","img/up-g.png");
Now, if these are in a container where they're the only .up
and .down
(a table row, say, where they're the only ones in that row but of course there are others in other rows), it's a bit easier:
// The up case
$this.closest('.container').find('.down img').attr("src","img/dw-g.png");
// The down case
$this.closest('.container').find('.up img').attr("src","img/up-g.png");
Solution 2:
$(function() {
$('.up img').click( function(){
var $this=$(this);
var postDataUp = $this.attr('mod');
$.post('/votePost.php', {varUp: postDataUp}, function(o){
console.log(o);
$this.attr("src","img/up.png");
$this.parent().next().next().find("img").attr("src","img/dw-g.png");
}, 'json');
});
$('.down img').click( function(){
var postDataDw = $(this).attr('mod');
$.post('/votePost.php', {varDw: postDataDw}, function(o){
console.log(o);
$this.attr("src","img/dw.png");
$this.parent().next().next().find("img").attr("src","img/up-g.png");
}, 'json');
});
});
Solution 3:
try with
$(function() {
$('.up img').click( function(){
var postDataUp = $(this).attr('mod');
$(this).attr('submitting', 'true');
$.post('/votePost.php', {varUp: postDataUp}, function(o){
console.log(o);
$('.up img[submitting="true"]').attr("src","img/up.png");
$('.down img').attr("src","img/dw-g.png");
}, 'json');
});
$('.down img').click( function(){
var postDataDw = $(this).attr('mod');
$.post('/votePost.php', {varDw: postDataDw}, function(o){
console.log(o);
$(this).attr("src","img/dw.png");
$('.up img').attr("src","img/up-g.png");
}, 'json');
});
});
Edit: Try with a flag
Post a Comment for "Jquery - Only Change For Clicked Element, Not All With The Same Class"