[英]dynamically removing and adding onclick event
I am dynamically generating html string and add event to it like below 我正在动态生成html字符串并向其添加事件,如下所示
htmlString = "<a href='#' class='save' onclick='callFunc(" + 4 + ")'>";
I now need to dynamically remove this onclick event and readd again with different Id. 现在,我需要动态删除此onclick事件,并使用不同的ID再次读取。
How can i achieve it? 我该如何实现?
Assuming that callFunc
is a named function, you can nullify element.onclick
then add a new event that is bound to your new id: 假设
callFunc
是一个命名函数,则可以使element.onclick
无效,然后添加一个绑定到新ID的新事件:
var newId = 10;
var saveLink = document.querySelector('.save');
saveLink.onclick = null;
saveLink.onclick = callFunc.bind(saveLink, newId);
Example: https://jsfiddle.net/mqyyf0xu/ 示例: https : //jsfiddle.net/mqyyf0xu/
Edit : with the new information that you want to increment a count when the user clicks the link, I think you should modify your approach to something like this: 编辑 :使用您要在用户单击链接时增加计数的新信息,我认为您应该对以下方法进行修改:
HTML: HTML:
<a href="#" class="like" data-likes="0">Likes <span class="like-count">0</span></a>
Javascript: 使用Javascript:
var likeButton = document.querySelector('.like');
likeButton.onclick = function() {
var likeCountDisplay = this.querySelector('.like-count');
var likeCount = parseInt(this.getAttribute('data-likes'), 10) + 1;
this.setAttribute('data-likes', likeCount);
likeCountDisplay.textContent = likeCount;
}
Here is an updated fiddle: https://jsfiddle.net/mqyyf0xu/2/ 这是更新的小提琴: https : //jsfiddle.net/mqyyf0xu/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.