在动态创建的按钮上添加单击事件,这些按钮在单击时更改模式 h4 文本
Add on click event on dynamically created buttons that on click change modal h4 text
所以我动态创建了按钮,我想在它们上动态附加单击事件,从而更改模态 h4 文本。所以我有一个声明的 js 对象,并且 console.log(dataview[0].subDirs[0]);
它给了我postsview/postview001/1.txt
这就是我想要的。
所以我有对象和 im 使用.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]);
那么如何在动态创建的按钮上真正创建点击事件,这些按钮具有不同的点击功能
将事件绑定到容器(不是动态创建的元素)并将其委托给按钮。
如果我正确理解您的问题,可能会有这样的事情!
//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 :)
})
相关文章:
- 单击按钮以等待单击按钮
- 单击按钮后如何逐个调用分区,上一个分区将隐藏
- 当值更改时,在servlet中自动获取textarea值,无需单击按钮
- 单击按钮时循环浏览匹配的表
- 单击按钮后启动javascript提示
- 单击按钮时在灯箱中显示不同的内容
- 单击按钮时加载数据
- 如何在不需要单击按钮的情况下获取选项的值
- 单击按钮时显示随机字符串
- 在单击按钮前后禁用提交按钮
- 单击按钮即可在浏览器的新选项卡中打开 Sapui5 详细信息页面
- 单击按钮时Div Increment
- 若单击按钮,则更改Javascript中的变量
- 单击按钮更改加载到表中的JSON文件
- 如何在单击按钮时显示2行1列的表格
- 单击按钮前运行事件
- 如何删除父表行时;删除“;在React JS中单击按钮
- 如何创建一个表并在单击按钮时插入此标签和文本字段
- JavaScript-onClick将按钮ID或单击按钮的文本传递给函数
- 如何在单击按钮时显示一个分区,同时隐藏另一个分区