Jquery检查div是否包含2个id且不再包含的子节点

时间:2015-02-25 23:25:48

标签: javascript jquery

我正在设计一个拖拉机放弃问题。

问题的答案将有两个或更多答案..(本练习只有两个)

我可以让脚本识别其中一个元素是否在div中,但如果两个元素都在div中,我只想要一个正面结果。

如果div中有任何不正确的答案,它将不会返回正确的结果。

对于本练习箱1& 2是正确的答案。 方框3不正确。

$('.checkanswer').on('click', function(event) {
if ($(".targetbox").find(".ans1, .ans2").length > 0){ 
document.getElementById('showme').style.display = "block";
}
else {
alert("Hello! Boxes 1 & 2  are not in the correct place.");
}
});

这是JSFiddle的问题: DEMO LINK

3 个答案:

答案 0 :(得分:0)

更改正确性测试中的条件,利用目标框中只有拖动的答案是其子项:

$('.checkanswer').on('click', function(event) {
    if (
           $(".ans1").parent().hasClass("targetbox")
        && $(".ans2").parent().hasClass("targetbox")
        && !$(".ans3").parent().hasClass("targetbox")
    ) {
        document.getElementById('showme').style.display = "block";
    }
    else {
        alert("Hello! Boxes 1 & 2  are not in the correct place.");
    }
});

演示here

答案 1 :(得分:0)

你可以这样做:

 //question results
 $('.checkanswer').on('click', function (event) {
     if (    $(".targetbox .ans1").length > 0 
          && $(".targetbox .ans2").length > 0
          && $(".targetbox").children().length == 2) {
           document.getElementById('showme').style.display = "block";
       } 
       else {
         alert("Hello! Boxes 1 & 2  are not in the correct place.");
       }

Updated fiddle

答案 2 :(得分:0)

另一种方法是将支票中的find()电话分开,如下(下图)。

    //question results
    $('.checkanswer').on('click', function(event) {
    if ($(".targetbox").find(".ans1").length > 0 
       && $(".targetbox").find(".ans2").length > 0 
       && $(".targetbox").find(".ans3").length === 0){ 
       document.getElementById('showme').style.display = "block";
    }
    else {
       alert("Hello! Boxes 1 & 2  are not in the correct place.");
    }
    });