如果您有一个不断呈现/销毁的 HTML 元素,那么 HTML 的 Javascript 事件绑定(bind)是否持续存在,或者是否有必要将事件绑定(bind)/取消绑定(bind)作为创建/销毁周期的一部分?
我正在使用 D3 生成美国各县的 map 。此外,我正在生成一个工具提示叠加层,其中包含针对有效选择的点击事件按钮。
单击事件处理程序的一部分,我将模板的 HTML 绑定(bind)到工具提示元素,然后将 Javascript 事件处理程序绑定(bind)到所述 HTML
thisObj._tooltip.template = template : "<div id = 'tooltip_template'>" +
"<div class = 'county_data'></div>" +
"<img src = '/static/images/delete.png' width = '28' height = '28' class = 'delete_logo' id = 'close_tooltip' />" +
"<button id = 'add_prospective_market' class = 'tooltip_button'>Prospective Market</button>" +
"<button id = 'add_market' class = 'tooltip_button'>Market County</button>" +
"<button id = 'remove_market' class = 'tooltip_button'>Remove Market</button></div>"
thisObj._tooltip.tooltip.html(thisObj._tooltip.template)
.style("left", (d3.event.pageX + 10) + "px")
.style("top", (d3.event.pageY - 50) + "px")
.style("pointer-events" , "auto")
.style("width", "400px")
.style("height", "150px");
$(".county_data").text(d.name + ", " + d.properties.StateCode);
addTooltipHandlers();
thisObj._tooltip.tooltip.transition()
.duration(800)
.style("opacity", 1);
我通过以下方式将事件处理程序绑定(bind)到元素
var addTooltipHandlers = function(){
$("#add_market").on("click", function(){
console.log("Adding new Market")
});
$("#add_prospective_market").on("click", function(){
console.log("Adding new Prospective market")
});
$("#remove_market").on("click", function(){
console.log("Removing this market")
});
$("#close_tooltip")
.on("mouseover", function(){
$(this).css({"border-color" : "red", "opacity" : 1});
})
.on("mouseout", function(){
$(this).css({"border-color" : "black", "opacity" : 0.5});
})
.on("click", function(){
console.log("Closing tooltip");
d3.selectAll($("#" + thisObj._tooltip.county))
.style("fill", thisObj._currentCounty.color);
thisObj._tooltip.tooltip.transition()
.duration(500)
.style("opacity", 0)
.style("pointer-events", "none");
thisObj._tooltip.open = false;
removeTooltipHandlers();
});
}
由于工具提示只在屏幕上可见,直到关闭事件被注册,然后它被销毁,一旦事件监听器绑定(bind)到一个元素,当该元素被销毁并重新创建时,该绑定(bind)是否仍然存在?
最佳答案
为了使事件处理程序持久化,您必须使用 event delegation在 jquery 中
代替
$(...).on(event, handler)
使用
$(...).on(event, selector, handler)
例如
$('body').on('click','a.saveButton', saveHandler)
通过这种方式,您可以将事件处理程序附加到 body 元素,而不是可以销毁或添加到 DOM 的实际元素。因此处理程序将一直工作,直到您将其关闭。
对于所有全局事件处理程序更好的是,您可以使用事件命名空间,例如:
$('body').on('click.app','a.saveButton', saveHandler)
$('body').on('click.app','a.addButton', addHandler)
这将允许您一起关闭
所有这些:
$('body').off('.app')
更新:非常简单jsfiddle显示事件委托(delegate)。
关于Javascript 事件绑定(bind)持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19032597/