动态创建的元素的SetAttribute类-Javascript

SetAttribute Class of a dynamically created element - Javascript

本文关键字:-Javascript SetAttribute 元素 创建 动态      更新时间:2023-09-26

我正在动态创建一个超链接元素,并设置其属性类,以便在单击它时触发一个函数。

以下是用于动态创建超链接元素的代码:

editLink = document.createElement("a");
editLink.setAttribute("class", "edit-button");

这就是点击链接时应该发生的情况:

$(document).ready(function(){
    $('.edit-button').click(function(event){
    event.preventDefault(); 
    var docHeight = $(document).height();
    var scrollTop = $(window).scrollTop();
    $('.overlay').show().css({'top': scrollTop + 'px'});
    });
});

但单击它时不会发生任何事情。提前感谢:)

不确定是否将创建的元素添加到body中。我做了这些改变,它运行良好

var editLink = document.createElement("a");
editLink.setAttribute("class", "edit-button");
editLink.innerHTML = "Click"; // added text for testing
window.document.body.appendChild(editLink); // Appending to body
$(document).ready(function(){
  $('.edit-button').click(function(event){
    event.preventDefault(); 
   alert('1')
    var docHeight = $(document).height();
    var scrollTop = $(window).scrollTop();
    $('.overlay').show().css({'top': scrollTop + 'px'});
    });
});

jsfiddle

尝试这个

var editLink = document.createElement("a");
editLink.setAttribute("class", "edit-button");
editLink.innerHTML  = 'click';
document.body.appendChild(editLink);
$(function() {
    $('.edit-button').on('click',function(event){
    alert('clicked');
    event.preventDefault(); 
    var docHeight = $(document).height();
    var scrollTop = $(window).scrollTop();
    $('.overlay').show().css({'top': scrollTop + 'px'});
    });
});

https://jsfiddle.net/s718ay3g/1/

事件委派就是实现这一点的方法。

当您直接将事件添加到.edit-button时,在加载文档时,浏览器会将该事件侦听器仅附加到当前现有的.edit-button元素。对于具有相同类的新创建的元素,它不会自动执行。

您可以做的是将事件的biding和listener代码放在一个函数中,并在每次向DOM添加新元素时调用它。但这被认为是一种糟糕的做法。

欢迎,活动代表团。

其想法是将事件附加到非动态的父/祖先元素,并仅当事件目标是您指定的元素(与某种类似选择器的类或ID匹配)时才触发事件。

在您的情况下,更新后的事件绑定代码如下所示。

$(document.body).on("click", ".edit-button", function(){
    //whatever you want to do in here.
}); 

然后,您可以继续像以前那样将类添加到新创建的元素中。。。

var editLink = document.createElement("a");
editLink.setAttribute("class", "edit-button");

该活动仍然有效。

通过这种方式,您只附加一次事件。

如果按钮/链接将包含在容器div或类似容器中,请将事件附加到该容器而不是主体。

$(".class-of-the-container").on("click", ".edit-button", function(){
    //whatever you want to do in here.
});