gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:09:37 25 4
gpt4 key购买 nike

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com