gpt4 book ai didi

javascript - 单击功能不适用于动态创建的 div 类

转载 作者:搜寻专家 更新时间:2023-10-31 22:03:08 25 4
gpt4 key购买 nike

我不确定如何解决这个问题。

我在 HTML 中制作了一些按钮,并添加了一些数据属性。这些按钮有一个名为 roleBtn 的类,它将调用我的 jQuery roleBtnClicked 函数并获取 HTML 数据属性中的变量。

$(".roleBtn").click(roleBtnClicked);

function roleBtnClicked(event){
reg.roleName = $(this).html(); /* Get role name: Actor */
reg.blueBtn = $(this).data('blue'); /* Get blue-btn-1 */
reg.the_Num = $(this).data('num'); /* Get the number */
reg.modal_ID = $(this).data('modal'); /* Get modal-1 */

现在使用此信息,在单击 roleBtn 后会出现一个模态窗口,然后我有一个 doneButton 将关闭模态窗口并使用来自数据属性,然后动态生成新的 HTML。这个新的 HTML 将包含一个类为 blueBtn 的按钮。

我的问题是,我的 blueBtn 的点击功能无法在即时创建的蓝色按钮上运行。它将在手头已有类 blueBtn 的 div 上工作,但如果它是动态创建的则不起作用。

你知道解决这个问题的方法吗?还是我错过了一些简单的东西?

点击 doneButton 后,我有另一个函数可以创建新的 HTML,包括动态的 blueBtns:

$('.selected_row .choices-col-left').append('<div class="blueBtn-holder" id="blueBtnHolder-'+theNum+'"><div class="blueBtn" id="'+blueBtn+'" row="'+rowName+'" modal="'+modal_ID+'" num="'+theNum+'">'+roleName+'</div></div>');

我的蓝色按钮点击功能不起作用

$(".blueBtn").click(blueBtnClicked);

function blueBtnClicked(event){
alert("Where are you blueBtn on the fly?");
console.log("Where are you blueBtn on the fly?");
};

最佳答案

试试这个:-您需要使用 .on() 为动态创建的元素进行事件委托(delegate)

$(".selected_row").on('click', '.blueBtn', blueBtnClicked);

function blueBtnClicked(event){
alert("Where are you blueBtn on the fly?");
console.log("Where are you blueBtn on the fly?");
};

Demo

当你只绑定(bind)一个点击事件时,它只会绑定(bind)到现有的 DOM 元素,所以你想将该事件绑定(bind)到父元素,以后你添加的任何元素都将具有该容器的相同选择器可通过代表团获得。

From Jquery Docs

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.

关于javascript - 单击功能不适用于动态创建的 div 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362366/

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