jQuery - 单击一个元素会触发另一个元素

get*_*way 2 html javascript jquery image

我有这个jQuery的文件,但vote_up click handler一直相互冲突与vote_down click handler,当我点击它改变了vote_up元素vote_down元素:

jQuery脚本:

$(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");
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

jQuery和ajax请求很好,但src的更改是问题所在,因为当我点击向下投票时,它会更改vote_up图像!!

Poi*_*nty 5

您不能对两个不同的元素使用相同的"id"值.

  • @getaway - 只要它是唯一的,您可以根据需要将其更改为"van_halen_1984".:O) (6认同)
  • @colinmarc好吧; 这意味着"在世界上独一无二,如完美的雪花或珍贵的鸭宝宝". (2认同)