jquery - 如何使用jQuery区分嵌套元素标签的点击功能?

标签 jquery

我有两个嵌套的元素,我想创建两个单击功能。我的正文标记用于完整页面,并且我有一个位于正文标记内的按钮标记。

当用户单击按钮时,我想在输入文本框中添加文本。当用户单击按钮外部(位于正文标记内部)时,我必须从文本框中删除文本。

$(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>

最佳答案

虽然可以在 body 点击处理程序中识别被点击的元素,但在 button 中调用 stopPropagation() 会容易得多 code> 单击处理程序以完全停止事件冒泡:

$(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>

关于jquery - 如何使用jQuery区分嵌套元素标签的点击功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52736043/

相关文章:

jquery动画与手机

php - 如何使用 jquery 或 javascript 在 php 中打开表单提交的弹出窗口

javascript - 可编辑的 Div - 点击时突出显示特定字母

javascript - 我需要在单击页面中的链接时切换样式表,以便页面以不同的颜色主题显示

jquery - 使用 jQuery.animate 在 Adob​​e AIR 中制作动画

javascript - jQuery - 取消选中复选框

javascript - span inside 按钮,在 Firefox 中不可点击

javascript - element.style.backgroundColor 不适用于 WordPress

jquery - Wordpress 视频的 100% 宽度和高度(水平滚动)

javascript - jQuery-onclick : Why does it execute click right on adding handler?