我有特定电影的多个thumbsup和thumbsdown元素,用户可以在其中竖起大拇指和竖起大拇指。我需要在单击时更改类的背景图像,但仅适用于特定的<a>
元素。我似乎无法正确使用.this
选项来定位该特定记录,因此它仅在单击时更改该特定元素的背景图像。
现在,此代码会在单击时更改所有元素的图像。例如,如果我点击thumbsup
,那么无论id
我的HTML
<a class="thumbsup" id="1"></a>
<a class="thumbsdown" id="1"></a>
<a class="thumbsup" id="2"></a>
<a class="thumbsdown" id="2"></a>
<a class="thumbsup" id="3"></a>
<a class="thumbsdown" id="3"></a>
我的jquery代码
$( ".thumbsup" ).live("click", function(){
movie_id = this.id;
$.ajax({
type: "POST",
url: "includes/voting.php?",
data: "movie_id="+ movie_id+
"&thumbsup=1",
success: function(data) {
$('.thumbsup').css("background-image", "url(/images/thumbs_up_hover.png)");
$('.thumbsdown').css("background-image", "url(/images/thumbs_down.png)");
}
});
return false;
});
$( ".thumbsdown" ).live("click", function(){
movie_id = this.id;
$.ajax({
type: "POST",
url: "includes/voting.php?",
data: "movie_id="+ movie_id+
"&thumbsdown=1",
success: function(data) {
$('.thumbsdown').css("background-image", "url(/images/thumbs_down_hover.png)");
$('.thumbsup').css("background-image", "url(/images/thumbs_up.png)");
}
});
return false;
});
答案 0 :(得分:1)
尝试将unique ID
用于所有元素:
$( ".thumbsup" ).live("click", function(){
movie_id = this.id;//you can use this id to change image of specific element
$.ajax({
type: "POST",
url: "includes/voting.php?",
data: "movie_id="+ movie_id+
"&thumbsup=1",
success: function(data) {
$('#'+movie_id).css("background-image", "url(/images/thumbs_up_hover.png)");
}
});
return false;
});
答案 1 :(得分:1)
多次使用ID是无效的HTML,我建议使用数据属性,因为你需要在ajax调用中使用id,因此六个不同的ID可能不合适:
<button class="thumbsup" data-id="1"></button>
<button class="thumbsdown" data-id="1"></button>
<button class="thumbsup" data-id="2"></button>
<button class="thumbsdown" data-id="2"></button>
<button class="thumbsup" data-id="3"></button>
<button class="thumbsdown" data-id="3"></button>
然后你可以在你的函数中获取id
movie_id = $(this).data('id');
然后再次使用data-id属性更新两个按钮
$('.thumbsup[data-id=' + movie_id + ']').css("background-image", "url(/images/thumbs_up_hover.png)");
$('.thumbsdown[data-id=' + movie_id + ']').css("background-image", "url(/images/thumbs_down.png)");