gpt4 book ai didi

jquery :button selector not able to handle dynamic button fields

转载 作者:行者123 更新时间:2023-12-01 06:52:49 25 4
gpt4 key购买 nike

在下面的代码中,jquery 选择器 $(":button") 能够选择 (+) 按钮。

但是,当我根据下拉菜单的选定值创建新按钮时。同一选择器无法选择新的 (-) 按钮。

附上代码:

 <script>
$(document).ready(function () {
$(":button").click(function () {
alert("here");
})
});

</script>

<select id="thing" name="garden" >
<option id="u" selected="selected" ></option>
<option id="1" > Flowers </option>
<option id="2" > Shrubs </option>
<option id="3" > Trees </option>
<option id="4" > Bushes </option>
<option id="5" > Grass</option>
<option id="6" > Dirt</option>

</select>

<button> + </button>

<div id="area"></div>

<button> + </button>
<script>
$("#thing").change(function () {
var str = "";
var id="";
var num=1;
$("#thing option:selected").each(function () {
str += $(this).text() + " ";
id = $(this).attr('id');
$("#"+id).attr('disabled',"disabled");
});
if (id != "u") {
var tx=$("#area").html();
var button="<button>-</button>";
$("#area").html(tx+"<div>"+str+" "+button+"</div>");
};
}).trigger('change');
</script>

最佳答案

$(document).on('click', 'button', function () {
alert("here");
});

这是一个委托(delegate)事件处理程序,这意味着它可以处理动态添加的元素。来自 on method 的 jQuery 文档:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

关于jquery :button selector not able to handle dynamic button fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12216040/

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