所以我动态创建了按钮,我想动态追加它们的click事件,这会改变模态h4文本。
所以我有一个声明的js对象和
console.log(dataview[0].subDirs[0]);
它给了我postsview/postview001/1.txt
这就是我想要的。
所以我有对象和我在这个对象中使用.txt文件的文件我有这些.txt文件的文件路径我想要的是将click事件添加到我动态创建的按钮,第一个按钮改变模态h4文本等于frist .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]);
那么如何在动态创建的按钮上真正创建点击事件,这些按钮具有不同的点击功能
答案 0 :(得分:1)
将事件绑定到容器(不是动态创建的元素)并将其委托给按钮。
如果我理解你的问题,可能会出现这样的事情!
//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 :)
})