首页 > 解决方案 > 如何在jQuery中的点击功能上使用else if条件?

问题描述

我正在制作一个卢多游戏,所以如果我单击 4 个框中的任何一个框(例如r1r2r3r4点击)。我尝试else if了条件,但它不起作用。请帮帮我。

这里r1,r2和是s'r3的盒子。r4id

我想做的事情:

if ($('#r1').click()) {
  $('#r1').click(function() {
    $(this).css("position", "absolute");
    $(this).animate((P[0]), 1000);
  });
} else if ($('#r2').click()) {
  $('#r2').click(function() {
    $(this).css("position", "absolute");
    $(this).animate((P[0]), 1000);
  });
} else if ($('#r3').click()) {
  $('#r3').click(function() {
    $(this).css("position", "absolute");
    $(this).animate((P[0]), 1000);
  });
} else if ($('#r4').click()) {
  $('#r2').click(function() {
    $(this).css("position", "absolute");
    $(this).animate((P[0]), 1000);
  });
}

标签: javascriptjquery

解决方案


$(".btn").on("click",function(){
    var _ID=this.id;
    if(_ID=="#r1")
        $(this).css("background-color","red");
    else if(_ID=="#r2")
        $(this).css("background-color","yellow");
    else if(_ID=="#r3")
        $(this).css("background-color","green");
    else if(_ID=="#r4")
        $(this).css("background-color","blue");
        
    console.log(_ID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="#r1" class="btn">click1</button>
<button type="button" id="#r2" class="btn">click2</button>
<button type="button" id="#r3" class="btn">click3</button>
<button type="button" id="#r4" class="btn">click4</button>


推荐阅读