在动态创建的按钮上添加单击事件,这些按钮在单击时更改模式 h4 文本

Add on click event on dynamically created buttons that on click change modal h4 text

本文关键字:单击 按钮 文本 h4 模式 事件 创建 动态 添加      更新时间:2023-09-26

所以我动态创建了按钮,我想在它们上动态附加单击事件,从而更改模态 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 :)
})