计算JavaScript中的出现次数

Jor*_*nen 0 javascript webkit drag-and-drop

我正在使用JavaScript库为iPad和iPad构建一个简单的益智应用程序来拖放碎片.我无法弄清楚如何检查所有部件是否在正确的位置.

到目前为止我得到的是

// create the draggable puzzle piece
var p1=document.getElementById('piece1');
new webkit_draggable(p1);
p1.className = 'ps1';

// create an array to count the pieces placed correctly
var countArray = new Array();

// create the dropspot, link it to the puzzle piece and add an element to the array to count. Finally kill the dropspot
var p1p1 = webkit_drop.add('droppiece1',{accept : ['ps1'], onDrop : function(){countArray.push("a");webkit_drop.remove('droppiece1')}});


// piece has been placed correctly.
if(countArray.length = 1){
alert('Piece placed correctly');
};
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是来自计数功能的警报立即触发.我怎样才能解决这个问题?

Rob*_*jic 5

将最后三行更改为:

// piece has been placed correctly.
if(countArray.length == 1){
alert('Piece placed correctly');
};
Run Code Online (Sandbox Code Playgroud)

你试图分配,而不是检查是否相等.

编辑:那么,它仍然不适合你?在我看来你是在onDrop上设置一个监听器,但是在你完成之后直接建立一个监听器(大概是在onDrop事件被触发之前)你正在检查是否有任何"丢弃".看看这不起作用?如果你只是想看看该事件实际上得到触发,而"一",其实是在被推到数组您可以在最后三行移动你的回调中.像这样:

// create the draggable puzzle piece
var p1 = document.getElementById('piece1');
new webkit_draggable(p1);
p1.className = 'ps1';

// create an array to count the pieces placed correctly
var countArray = new Array();

// create the dropspot, link it to the puzzle piece and add an element to the array to count. Finally kill the dropspot
var p1p1 = webkit_drop.add('droppiece1', {accept: ['ps1'], onDrop: function() {
    countArray.push("a");
    webkit_drop.remove('droppiece1');

    // piece has been placed correctly.
    if (countArray.length == 1) {
        alert('Piece placed correctly');
    }
}});
Run Code Online (Sandbox Code Playgroud)

我还没有真正测试过,但是这里有一个版本,其中包含所有webkit的东西,只需点击一下即可删除:http://jsfiddle.net/kajic/snJMr/1/

如果你点击红色框,那么当你放弃这件作品时,你的ipad应用程序会发生什么?