代码之家  ›  专栏  ›  技术社区  ›  user9050678

Javascript返回false和事件.目标

  •  0
  • user9050678  · 技术社区  · 7 年前

    有人能解释一下为什么 button1 不会被俘吗?我知道 return false 在事件上 click 将停止传播,但仍应通过 document.addEventListener('click', function(e) {console.log(e.target);}); 因为我们试图通过 e.target

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#button1").click(function(){
           return false;
        });
    });
    </script>
    </head>
    <body>
    
    <button id="button1">Button1 (dont get captured)</button>
    <button id="button2">Button2 (get captured)</button>
    
      <script>
        document.addEventListener('click', function(e) { 
         console.log(e.target);});
      </script>
    </body>
    </html>

    $("#button1").click(function(){return false}); ,但仍然想捕捉

    按钮1 document.getElementById("button1").addEventListener("click", function(e){console.log(e.target)}); 在现实中,有许多我想要捕获的元素(使用不同的类和id),为每个元素添加一个事件侦听器是不切实际的,我只展示了一个按钮作为示例。,我只想记录单击的元素。

    我无法更改页面的jQuery代码或HTML,我只想在chrome控制台中运行一些测试,为此我想捕获单击的每个元素

    谢谢

    2 回复  |  直到 7 年前
        1
  •  1
  •   Meziane    7 年前

    返回false;防止浏览器执行button1链接的默认操作。

    等效代码 return false 是:

    $('.button1')
       .click(function (event) {
           event.preventDefault();
           event.stopPropagation();
    });
    

    如果你只是想停止传播使用 stopPropagation()

    看一看 this ,并阅读更多有关 preventDefault() stopPropagation()

        2
  •  0
  •   user9050678    7 年前

    不是很有效率,但对我有用

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#button1").click(function(){
           return false;
        });
    });
    </script>
    </head>
    <body>
    
    <button id="button1">Button1 (dont get captured)</button>
    <button id="button2">Button2 (get captured)</button>
    
      <script>
     elements = document.querySelectorAll('body *');
    elements.forEach(function(elem) {
        elem.addEventListener('click', function(e){
          console.log(e.target); // or simply console.log(elem)
    });
        });
      </script>
    </body>
    </html>

    感谢所有人,尤其是@mplungjan给了我这个想法