Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript堆栈执行问题_Javascript_Stack_Execution - Fatal编程技术网

JavaScript堆栈执行问题

JavaScript堆栈执行问题,javascript,stack,execution,Javascript,Stack,Execution,我的功能有什么问题?为什么它打印多次而不是一次 $('document').ready(function(){ //click a button dozen times it invokes submit and write message in console.log $('button').live('click', function(){ $this = $(this); submit($this); //this function mayb

我的功能有什么问题?为什么它打印多次而不是一次

$('document').ready(function(){

    //click a button dozen times it invokes submit and write message in console.log
    $('button').live('click', function(){ 
       $this = $(this);
       submit($this); //this function maybe push in stack a lot of times 
   });

});

function submit($this){
   img = $this.nextAll(".submit");

   // and when I click on image it must write one time but it writes a lot of times                                   
   img.on('click', function(){                      
      console.log($this.text() + " ----> click"); // 
   });
}

看起来问题在于每次调用函数时都将click事件绑定到img,但您从未删除它

  // and when I click on image it must write one time but it writes a lot of times                                   
  img.on('click', function(){                      
     console.log($this.text() + " ----> click"); // 
  });

我会在函数之外添加click事件。

您不应该使用
live
,它已被弃用,您可以这样编写

$(document).ready(function(){
    $(document).on('click', 'button', function(){ 
       img = $(this).nextAll(".submit");
       img.off('click').on('click', function(){                      
           console.log($(this).text() + " ----> click"); // 
       });
    });
});

使用
off
取消注册先前添加的
单击
事件,使其仅触发一次

更新: 以下内容可以替换
实时
。您可以使用父包装而不是
文档


很难判断代码是怎么回事。你能编辑这个例子并将其正确格式化以突出显示语法吗?我必须把它放在里面,因为我通过点击图片来发送按钮的值。所以,如果我把它放在外面,我就失去了对纽扣对象的引用。当我点击按钮时,显示发送点击按钮值的图像。问题是我有很多不同值的按钮,所以我必须知道我点击了哪个按钮。我认为问题更严重…谢谢!它真的帮助了我。我认为问题在于堆栈执行或更深层,但现在我发现我错了。再次感谢你,你节省了我的时间!我知道live已被弃用,但我没有选择权—数据会动态添加到页面中,所以只有live可以一次又一次深入DOM,将事件绑定到我的按钮。它可以工作,我不知道更好的解决方案。@YaroslavNychka,检查更新的答案。好的,我知道了)使用on()而不是live(),将来我将避免许多问题您不需要在
$(document)中这样做。如果您只绑定到
document
节点,准备好了吗。
$(document).on('click', 'button', function(){ ... });