我有一个静态和动态生成的搜索输入框。当我在搜索框中输入一个值并单击"x“以清除它时,我会得到静态搜索框的触发器,但是当我单击"x”时,动态生成的值不会发生任何变化。示例代码如下:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div id="search_group" style="">
<div class="input-group">
<input type="search" class="form-control" id="search_text"/>
</div>
</div>
<h5 id="add_search" style="cursor:pointer">Dynamically ad Search Box</h5>
<p id="append_here"></p>
<script type="text/javascript">
//this works on the static search box, but not on the dynamic search box
$('input[type=search]').on('search', function () {
console.log('X clicked');
});
//add search box dynamically
$( "#add_search" ).on( "click", function() {
var new_search_element = `<div id="search_group">
<div class="input-group">
<input type="search" class="form-control" id="search_text"/>
</div>
</div>`;
$("#append_here").empty().append(new_search_element);
});
</script
</body>
</html>如何使动态生成的搜索框响应对"x“的单击?
感谢你的帮助!
发布于 2022-11-15 00:25:01
我认为你应该学习“事件冒泡”
易于粘贴此链接
https://bokboot.net/read?id=62&key=fdfd681c-1807-4e93-9ca4-b0f68a6717b5
$('#search_group').on('search', function (e) {
if(e.target.id != "search_text") return;
console.log('X clicked');
$("#data").empty();
});https://stackoverflow.com/questions/74439365
复制相似问题