奇怪的javascript行为onClick on div with cordova

时间:2015-10-02 13:56:55

标签: javascript cordova

我已经设置了一个小项目...我有一些div,当我点击其中一个div我想得到它的id并且现在显示带有id的警报,之后我想要重定向到一个将获取其ID并执行一些操作的页面。我的js是:

  function onLoad() {

        document.addEventListener("deviceready", onDeviceReady, false);

      //  alert("loaddddddd");
    }

    function reply_click(clicked_id)
    {
       alert(clicked_id);
    }
    function onDeviceReady() {
        //occorrerà rendere dinamica questa ricerca
        //alert("aaa");

        var div = document.getElementById('c1');


        for(var i=1;i<=7;i++){


            var div = document.getElementById('c'+i);

            div.addEventListener("click",reply_click(i));
        }

      }

问题是当它在我点击任何内容之前循环遍历div时它会显示所有警报...而当我点击它时显然没有显示任何内容 谢谢

2 个答案:

答案 0 :(得分:1)

解决方案1:从reply_click(n)返回一个警告正确n的函数。 reply_click函数变为closure

function reply_click(clicked_id){
  var id = clicked_id;
  return function(){
    alert( id );
  }
}
function onDeviceReady() {
    for(var i=1;i<=7;i++){
        var div = document.getElementById('c'+i);
        // here the reply_click is called immediately, 
        // but returns another function which is added as event handler
        div.addEventListener("click",reply_click(i));
    }
}

http://jsfiddle.net/g8qfpn7L/

解决方案2:bind reply_click到一个对象,然后提醒该对象的属性:

function reply_click(){
    alert( this.id );
}
function onDeviceReady() {
    for(var i=1;i<=7;i++){
        var div = document.getElementById('c'+i);
        // here we bind reply_click to an object with id property, 
        // and the bound function is called in event handler
        div.addEventListener("click",reply_click.bind({ id : i }));
    }
}

http://jsfiddle.net/g8qfpn7L/1/

答案 1 :(得分:0)

为什么不在文档中添加事件侦听器呢?可能是一个更好的选择,使您的代码更简单。

var elements = ["c1","c2","c3"]; //eligible dom elements

//add the event listener just once on the document level
document.addEventListener("click", function(event){
        var targetElement = event.target || event.srcElement;
        if (elements.indexOf(targetElement.id) >= 0)
           reply_click(targetElement.id);
});