【问题标题】:Jquery click function for a div, but not for link inside div?一个div的jQuery点击功能,但不是div内的链接?
【发布时间】:2016-09-03 19:05:51
【问题描述】:

我有一个点击功能,当用户点击 div 中的任意位置时,它运行成功。但是,div 内有一个链接。如果用户单击链接,我不想运行该功能,以便用户在单击时转到链接 url。

html

<div id="container">
<a href="http://www.example.org"></a>
</div>

jQuery

$(document.body).on('click', '[id="container"]' ,function(){
// do whatever
});

我应该使用哪种方法来实现?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以检查点击的目标如下:

    $(document.body).on('click', '#container' ,function(e){
        if (e.target.id !== 'container') return; // not the element we want
        // do whatever
    });
    

    或者,如果应该允许 div 的任何其他子元素,除非它是 a 元素,那么:

    $(document.body).on('click', '#container' ,function(e){
        if (e.target.tagName === 'A') return; // not the element we want
        // do whatever
    });
    

    【讨论】:

    • 仅供参考 [id="container"] 通常写成 #container
    • 仅供参考,因为内容是动态添加的。
    • 仅供参考,您仍然可以使用'#container'
    【解决方案2】:

    我相信如果你做这样的事情,应该可以工作:

        $("#container a").click(function(e) {
            e.stopPropagation();
       });
    

    希望对您有所帮助! :)

    【讨论】:

      【解决方案3】:

      试试这个:

      $(document).ready(function(){
      
          $("#container").on("click",function(e){
      
              if(e.target.tagName == "DIV") {
                  fun();
              }
      
      
              else if(e.target.tagName == "A") {
                  e.stopPropagation();
                  }
      
      
          })
      
          function fun() {
              alert("Run function");
          }
      })
      

      最终代码:

      <html>
          <title>This is test</title>
          <head>
          </head>
          <body>
              <div id="container">div
                 <a href="http://www.example.org">Link</a>
              </div>
              
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
              <script>
          $(document).ready(function(){
      
              $("#container").on("click",function(e){
      
                  if(e.target.tagName == "DIV") {
                      fun();
                  }
      
      
                  else if(e.target.tagName == "A") {
                      e.stopPropagation();
                      }
      
      
              })
      
              function fun() {
                  alert("Run function");
              }
          })
              </script>
          </body>
      </html>

      【讨论】:

        【解决方案4】:
        $(document).on('click', 'a',function (evt) {
            evt.stopPropagation();
        });
        

        【讨论】:

          猜你喜欢
          • 2018-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多