为什么连接的 onclick 事件不触发?
我正在开发一个自定义的 dojo-widget。在小部件中,我动态创建一些 DOM 节点并将函数连接到它们的事件。
我的代码看起来与此类似:
var treeItem = document.createElement("div");
if (current.children) // 'current' is set up like: { id: <int>, name: <string>[, children: <id-array>] }
{
var treeItemExpander = document.createElement("img");
[...] // stuff like setting classes and setting the path, nothing special
dojo.connect(treeItemExpander, "onclick", function () { alert("test expander"); }); // problem line
treeItem.appendChild(treeItemExpander);
}
treeItem.innerHTML += current.name;
dojo.connect(treeItem, "onclick", function () { alert("test item"); });
this.tree.appendChild(treeItem);
现在,正如您可能从注释中猜测到的那样,条件嵌套元素上的事件不会被触发。
即使我注释掉了 treeItem
上的连接(顺便说一句,它可以工作),我也没有成功。我尝试了 treeItemExpander.onclick = function () {...}
也无济于事。唯一有效但在小部件中没有任何意义的是 treeItemExpander.setAttribute("onClick", "alert('test');");
。
编辑:我解决了这个问题:http://jsfiddle.net/YCJ6X/< /a>
编辑:jovica(在 dojo-IRC)发现 ubuntu 上的 Chrome 中不会出现该问题。
那么如何将事件附加到该图像上呢?
I'm working on a custom dojo-widget. Within the widget I am creating some DOM-Nodes dynamically and connect functions to their events.
My code looks similar to this:
var treeItem = document.createElement("div");
if (current.children) // 'current' is set up like: { id: <int>, name: <string>[, children: <id-array>] }
{
var treeItemExpander = document.createElement("img");
[...] // stuff like setting classes and setting the path, nothing special
dojo.connect(treeItemExpander, "onclick", function () { alert("test expander"); }); // problem line
treeItem.appendChild(treeItemExpander);
}
treeItem.innerHTML += current.name;
dojo.connect(treeItem, "onclick", function () { alert("test item"); });
this.tree.appendChild(treeItem);
Now, as you can probably guess from the comments, the event on the conditionally nested element doesn't get triggered.
Even when i commented out the connect on treeItem
(which works by the way), I had no success. I tried treeItemExpander.onclick = function () {...}
to no avail as well. The only thing that worked, but makes no sense in a widget was treeItemExpander.setAttribute("onClick", "alert('test');");
.
Edit: I made a fiddle with the issue: http://jsfiddle.net/YCJ6X/
Edit: jovica (at the dojo-IRC) found out that the problem does not occur in Chrome on ubuntu.
So how do I get an event attached to that image?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
beuss 在 Dojo-IRC 上回答:
修改
innerHTML
也会更改之前附加的 DOM 节点。附加文本节点而不是直接写入文本可以解决该问题。更新的小提琴: http://jsfiddle.net/YCJ6X/1/
Answered by beuss on the Dojo-IRC:
Modifying
innerHTML
changes previously appended DOM nodes as well. Appending a text node instead of writing the text directly solves the issue.Updated fiddle: http://jsfiddle.net/YCJ6X/1/
尝试在附加元素后附加事件。
我认为这会解决你的问题。
Try to attach the event after you append the element.
I think that would solve your problem.