gpt4 book ai didi

javascript - 在动态创建的按钮上添加单击事件,单击后更改模态 h4 文本

转载 作者:行者123 更新时间:2023-12-03 07:33:08 26 4
gpt4 key购买 nike

所以我动态创建了按钮,并且我想动态附加到它们上的单击事件,这会更改模态 h4 文本。所以我有一个声明的 js 对象和console.log(dataview[0].subDirs[0]);

它给了我 postsview/postview001/1.txt 这就是我想要的。

所以我有对象,我使用 .txt 文件作为该对象中的文本,我有这些 .txt 文件的文件路径,我想要的是将单击事件添加到我的动态创建的按钮中,并且第一个按钮将模态 h4 文本更改为等于第一个.txt文件内容

  //So this is the function that gets the text of the .txt file and append it to the modal h4

function appendmodalheader(path){
$.ajax({
url : path,
async: false,
dataType: "text",
success : function (txtcontent) {
$('#mod-header').text(txtcontent);
}
});
}
//this is a loop where i loop through all .txt files and for each file
//I'm appending on click event to the related button
// buttons id are submit0, submit1, ...


for (var i = 0; i < dataview.length; i++){
$('#submit' + i).on('click', function(){
appendmodalheader(dataview[i].subDirs[0]);
$('#myModal').modal('show');
});
}

问题是下面的脚本似乎不起作用,并且 modal.('show'); 因此没有执行

appendmodalheader(dataview[i].subDirs[0]);

那么如何在动态创建的按钮上真正创建点击事件,这些按钮具有不同的点击功能

最佳答案

将事件绑定(bind)到容器(不是动态创建的元素)并将其委托(delegate)给按钮。

如果我正确理解你的问题,可能会出现这样的情况!

//Lets say all your buttons are inside a container with class 'foo'
//Add a common class for your buttons to which the event will be delegated
//have the 'i' of your example as data-id (or any data attribute of your choice :)) to the button
$('.foo').on('click','.buttonCalss',function(){
var id = $(this).data('id');//identifying which button is clicked
appendmodalheader(dataview[i].subDirs[0]);
$('#myModal').modal('show');
});

添加数据属性语法:

$("<button />",{text : 'Разгледай', type : 'button', class : 'btn btn-information', id:id}).appendTo(post).data('id',id);

检索 ID:

$(post).on('click','.btn',function(){
var id = $(this).data('id');
//Do anything with that :)
})

关于javascript - 在动态创建的按钮上添加单击事件,单击后更改模态 h4 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35731484/

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