计算JavaScript中的出现次数

时间:2012-03-08 17:36:04

标签: javascript drag-and-drop webkit

我正在使用JavaScript library为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');
};

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

2 个答案:

答案 0 :(得分:5)

将最后三行更改为:

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

您尝试分配,而不是检查是否相等。

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

// 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');
    }
}});

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

如果您单击红色框,那么当您放下该文件时,您希望在ipad应用程序上发生什么?

答案 1 :(得分:4)

你应该改变这个

if(countArray.length = 1){

if(countArray.length == 1){
                  // ^^ use comparison, not assignment

第一行 1分配给countArray.length,后者解析为1,这是真实的。