代码之家  ›  专栏  ›  技术社区  ›  Liam neesan

如何使用jQuery区分嵌套元素标记的click函数?

  •  2
  • Liam neesan  · 技术社区  · 6 年前

    当用户单击按钮时,我想在输入文本框中添加文本。当用户在body标签内的按钮外单击时,我必须从文本框中删除文本。

    $(document).ready(function() {
      $("button").click(function() {
        alert("only button is clicked");
        $("input:text").val("Test");
      });
    
      $("body").click(function() {
        alert("body clicked");
      });
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" id="setName" value="" /><br/><br/><br/>
    <button>Set the value of the input field</button>
    3 回复  |  直到 6 年前
        1
  •  2
  •   T.J. Crowder    6 年前

    Rory's answer 像往常一样准时。另一种选择是只在上使用一个处理程序 body 使用 closest 要确定单击是否在传递到body的过程中通过了按钮,请参见注释:

    $(document).ready(function() {
      $("body").click(function(e) {
        // Did this click pass through the button?
        if ($(e.target).closest("button").length) {
          // Yes
          alert("only button is clicked");
          $("input:text").val("Test");
        } else {
          // No
          alert("body clicked");
        }
      });
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" id="setName" value="" /><br/><br/><br/>
    <button>Set the value of the input field</button>
        2
  •  7
  •   Rory McCrossan Hsm Sharique Hasan    6 年前

    body 单击handler,只需调用 stopPropagation() button

    $(document).ready(function() {
      $("button").click(function(e) {
        e.stopPropagation();
        console.log("only button is clicked");
        $("input:text").val("Test");
      });
    
      $("body").click(function() {
        console.log("body clicked");
        $("input:text").val(''); // add this line to remove the text
      });
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" id="setName" value="" /><br/><br/><br/>
    <button>Set the value of the input field</button>
        3
  •  0
  •   Ajay    6 年前

    您可以通过event.target跟踪单击的任何元素的目标,然后执行必要的操作

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <body class="container">   
        <input type="text" id="setName" value="" />
        <button id="samplebtn">Set the value of the input field</button>
    </body>
    
    
    $("body").click(function(event) {
        if (event.target.id == "samplebtn") {
            //do button related work
        } else {
            //do other stuff
        }
    });