Javascript 动态HTML上treeview插件的JQuery注册点击事件
我使用jQueryTreeView插件将数据显示为树结构。 问题是我正在从JSON响应对象动态生成HTML。 这从来没有像预期的那样有效。没有为单击事件注册元素Javascript 动态HTML上treeview插件的JQuery注册点击事件,javascript,jquery,treeview,Javascript,Jquery,Treeview,我使用jQueryTreeView插件将数据显示为树结构。 问题是我正在从JSON响应对象动态生成HTML。 这从来没有像预期的那样有效。没有为单击事件注册元素 function show(jsonResp) { //Parsing the JSON response and building HTML on the fly. $red = ''; for (var i = 0; i < treeElements.length; i++) { $r
function show(jsonResp) {
//Parsing the JSON response and building HTML on the fly.
$red = '';
for (var i = 0; i < treeElements.length; i++) {
$red = $red + treeElements[i];
}
$("#user-records").append($red);
$("#red").treeview({
animated: "fast",
collapsed: true,
unique: true,
persist: "cookie",
toggle: function () {
window.console && console.log("%o was toggled", this);
}
});
}
如果我硬编码动态HTML,我就能看到预期的结果。我调试并理解JQuery为现有HTML元素注册单击事件,但不是动态形成的元素。请让我知道如何为点击事件注册它们
function show(jsonResp) {
//Parsing the JSON response and building HTML on the fly.
$red = '';
for (var i = 0; i < treeElements.length; i++) {
$red = $red + treeElements[i];
}
$("#user-records").append($red);
$("#red").treeview({
animated: "fast",
collapsed: true,
unique: true,
persist: "cookie",
toggle: function () {
window.console && console.log("%o was toggled", this);
}
});
}
我在chrome中调试并检查我的新div是否已注册到click事件。但当我点击时,什么都没有发生
附言:如果我复制生成的HTML元素的控制台日志,并创建一个不同的页面,它就可以完美地工作。唯一的问题是动态添加HTML代码时。我不知道在哪里注册这个新添加的动态HTML代码的点击事件。你这样做了吗
$(document).on("click", ".selector", function() {
// your code
});
使用此代码,您可以在生成的内容上绑定事件。下面是一个示例:更改此选项
this.find("div." + CLASSES.hitarea).click( toggler );
对此
$(document).on('click', "div." + CLASSES.hitarea, toggler);
这将导致
“div.”+CLASSES.hitarea的所有未来实例尊重您提供的单击处理程序。您是否使用将事件委派给新内容,请添加您正在使用的代码,以便我们可以看到可能出现的问题be@PatrickEvans请看一看我添加的代码。为什么要在(其中一些)前面加前缀您的变量是否具有$
?JavaScript不是PHP。何时何地调用this.find(“div.”+CLASSES.hitarea)。单击(切换)
也是jQuery(插件)函数中的一个,否则这个
将不是一个jQuery引用,它不能访问查找
或其他jQuery函数。这些点击事件由treeview插件处理。这个。查找(“div.”+CLASSES.hit区域)。单击(切换器);问题是,在我的动态HTML案例中,它们并没有发生