如果我使用.each方法,则Droppable不接受正确的输入

时间:2013-10-08 08:58:27

标签: javascript jquery

如果我在阵列上使用jQuery的每个方法,有人可以解释为什么droppable不接受正确的值。如果我使用相同代码的普通JavaScript for循环,它可以正常工作。

所以我不明白,为什么它不使用jQuery的每种方法?

以下提示和代码。
http://jsfiddle.net/BuGA9/

$(function() {
var answer = ["apple", "tree"];
$("p.sen").draggable({revert: 'invalid'});
$("#dropBox").droppable({
    accept: function(element){
        $word = element.text().trim();


        for (var index in answer) {
           if($word === answer[index] || rem($word) === answer[index] )  { 
            return true;
            } 
        }
        /*

        $(answer).each(function(index) {
            if($word === answer[index] || rem($word) === answer[index] )  {
            return true;
            } 
        });  
        */

    },
    drop: function(event, ui) {
        $( this )    
            .addClass("correct")
            .find( "p" )
                .html("Correct well done!!!!");   
   }
});
});

function rem(sentence) {
sentence = sentence.substring(0, sentence.length - 1);
return sentence;
}

感谢。

2 个答案:

答案 0 :(得分:1)

每个返回都返回迭代函数的值,而不是你的accept函数。您必须在范围外创建一个变量并进行设置,以便以后返回。

var isCorrect = false;            
 $(answer).each(function(index) {
 if($word === answer[index] || rem($word) === answer[index] )  {
   isCorrect = true;
   return false;
 } 
});  
return isCorrect;

另外,我建议你尽可能使用本机JavaScript循环 - 每个jQuery通常都有点慢。

http://jsperf.com/for-vs-foreach/37

答案 1 :(得分:0)

根据JQuery documentation

我们可以在特定的迭代中打破 $ .each()循环 通过使回调函数返回false 。返回非错误 是for循环中的与continue 语句相同;它会 立即跳到下一次迭代。