0

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

所以我不明白,为什么它不能与 jQuery each 方法一起使用?

小提琴和下面的代码。
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;
}

谢谢。

4

2 回答 2

1

each 中的 return 从迭代函数返回值,而不是您的接受函数。您必须在范围之外创建一个变量并设置它以便以后返回它。

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

于 2013-10-08T09:14:43.863 回答
0

根据JQuery 文档

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

于 2013-10-08T09:10:49.927 回答