【问题标题】:How to stop the effect of an event when another effect of the same event occur?当同一事件的另一个影响发生时,如何停止一个事件的影响?
【发布时间】:2013-05-29 15:13:32
【问题描述】:

认为这是 html 代码:

        <table>         
        <tr>
            <td><img id="a11" src="photos/empty.png" /></td>
            <td><img id="a12" src="photos/empty.png" /></td>
            <td><img id="a13" src="photos/empty.png" /></td>
        </tr>

        <tr>
            <td><img class="move" id="a21" src="photos/Pawn.png" /></td>
            <td><img class="move" id="a22" src="photos/Pawn.png" /></td>
            <td><img class="move" id="a23" src="photos/Pawn.png" /></td>
        </tr>
    </table>

认为“empty.png”只是一个空图像

这是 jQuery 代码:

$(document).ready(function() {

$(".move").click(function (){

    //reset the background color of the first row
    $("#a11, #a12, #a13" ).css("background-color" , "");

    //fetch the src attribute of the clicked element
    var src = $(this).attr("src");

    //fitch the id attribute of the clicked element
    var Id  = $(this).attr("id");
    var Id  = "#"+Id;
    var x = Id[2];
    var y = Id[3];

    ////////////////////////

    newx = x - 1;
    newsy = y;

    //form the new id of the above cell
    newId = "#a" + newx + newsy;

    //make the background of this cell 'red'
    $(newId).css("background-color","red");

    //fire event that when click on this cell move the image to it and remove the image from original cell
    $(newId).click(function(){

        $(Id).attr("src","photos/empty.png");
        $(this).attr("src",src);
        $("#a11, #a12, #a13" ).css("background-color" , "");


    });

});

});

必需:
当点击第二行的任意一个单元格时,上面对应的单元格的背景会变成红色

然后当点击它时,图像会移动到它。

问题

点击第一个单元格时出现问题(first pawn #a21)

然后在第二个单元格中单击一个(第二个棋子 #a22)

然后单击第三个单元格中的一个(第三个 pawn #a23)

然后点击#a13 或#a12 单元格...下面对应的图像将移动到它

我不想要它

我想移除上一个事件的效果,但只执行最后一个事件的效果

【问题讨论】:

    标签: jquery


    【解决方案1】:

    通过比较点击事件中的当前 id 来解决问题。

    $(newId).click(function(){
        var currentid = "#"+this.id;
        if(newId == currentid){
            $(Id).attr("src","photos/empty.png");
            $(this).attr("src",src);
            $("#a11, #a12, #a13" ).css("background-color" , "");
        }
    });
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多