简体   繁体   English

动态创建的锚标记上的Onclick事件

[英]Onclick event on dynamic created anchor tag

I have an anchor tag which created dynamically and this anchor tag has an onclick event like this: 我有一个动态创建的锚标记,并且此锚标记具有如下的onclick事件:

$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>" +  "<a href='javascript:void(0)' onclick='deleteEducationLevel(" + educationHistoryId + ");'>Delete</a>");

when I click on this anchor I got js error saying: 当我单击此锚点时,出现js错误消息:

TypeError: 'click' called on an object that does not implement interface HTMLElement. TypeError:在未实现接口HTMLElement的对象上调用了“ click”。

I suspect some character escaping issue but unable to resolve. 我怀疑某些字符转义问题,但无法解决。

Added 添加

generated html: 生成的html:

<div id="ff8081814734be020147357beda5002b"><span>A Level</span><a onclick="deleteEducationLevel(ff8081814734be020147357beda5002b);" href="#">Delete</a></div>

Try replacing that line with the following, so that the event is bound like this: 尝试用以下内容替换该行,以便事件绑定为:

var $link = $("<a href='javascript:void(0)'>Delete</a>");

$link.on("click", function() {
    deleteEducationLevel(educationHistoryId);
});

$('#'+educationHistoryId).append("<span>"+degreeTitle+"</span>").append($link);

In my (very reduced) test, this seems to work: http://jsfiddle.net/E7LRt/ 在我的测试中(非常简化),这似乎可行: http : //jsfiddle.net/E7LRt/

Is there an actual need to do this with just one line? 实际需要仅用一行吗? I'd suggest the following solution: 我建议以下解决方案:

var $anchor = $(document.createElement("a")).attr("href","javascript:").text("Delete").on("click",function() {
    alert("clicked!");
    alert("educationHistoryId: " + educationHistoryId);
});

$("body").append("<span>" + degreeTitle + "</span> ",$anchor);

This works great: Fiddle 这很棒: 提琴

I always try to prevent using inline eventhandlers. 我总是试图避免使用内联事件处理程序。 It's bad practise in my opinion. 我认为这是不好的做法。

Give the span a class and use event delegation. 给跨度一个类并使用事件委托。

You can then bind the click event to a existing parent(I am assuming element with id= "#"+educationHistoryId is existing when the event handler attachment takes place) and then delegate the event to the newly added link. 然后,您可以将click事件绑定到现有的父项(假设发生事件处理程序附件时, id= "#"+educationHistoryId元素存在),然后将事件委托给新添加的链接。

$("#"+educationHistoryId).on("click", <class>, function(){
 deleteEducationLevel(educationHistoryId);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM