最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - If statement executing even when false - Stack Overflow

programmeradmin1浏览0评论

So I have an if statement that checks the id of the draggable that was just dropped in the droppable. I have checked in the console using console.log to see if the the if statement is working properly. It is returning the right true/false value but even if it returns false it still executes the code and not the else. I haven't posted to much code because I am quite sure that it is a problem with my if statement and not with the code as a whole. The if statement executes regardless of what I put after the ===. I saw someone else had this problem and it was something to do with infinite recursion, but the answer was too specific to his code for me to understand.

$("#game1drop1").droppable ({
    drop: function(e,ui) {
        if ($(ui.draggable[0].id === "game1img1")) {
            $("#game1drop1").addClass("correct")}
        }
        else{
            $(ui.draggable[0]).addClass("positionWrong")
        }
    }   
});

So I have an if statement that checks the id of the draggable that was just dropped in the droppable. I have checked in the console using console.log to see if the the if statement is working properly. It is returning the right true/false value but even if it returns false it still executes the code and not the else. I haven't posted to much code because I am quite sure that it is a problem with my if statement and not with the code as a whole. The if statement executes regardless of what I put after the ===. I saw someone else had this problem and it was something to do with infinite recursion, but the answer was too specific to his code for me to understand.

$("#game1drop1").droppable ({
    drop: function(e,ui) {
        if ($(ui.draggable[0].id === "game1img1")) {
            $("#game1drop1").addClass("correct")}
        }
        else{
            $(ui.draggable[0]).addClass("positionWrong")
        }
    }   
});
Share Improve this question edited Oct 23, 2014 at 8:47 Brett Gregson 5,9233 gold badges44 silver badges60 bronze badges asked Oct 23, 2014 at 8:35 PeterPeter 553 silver badges9 bronze badges 1
  • 2 this expression is strange $(ui.draggable[0].id === "game1img1"), the whole boolean expression is put into $(...)? – King King Commented Oct 23, 2014 at 8:37
Add a ment  | 

1 Answer 1

Reset to default 7

It's because you have $() wrapped around your test. So it's equivalent to:

if ($(false)) {

This is wrapping false in a jQuery object, and all objects are truthy.

It should be:

if (ui.draggable[0].id === "game1img1") {
发布评论

评论列表(0)

  1. 暂无评论