简体   繁体   English

为什么连接的 onclick 事件不会触发?

[英]Why does a connected onclick event not fire?

I'm working on a custom dojo-widget.我正在开发一个自定义的 dojo-widget。 Within the widget I am creating some DOM-Nodes dynamically and connect functions to their events.在小部件中,我正在动态创建一些 DOM 节点并将函数连接到它们的事件。

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.即使我注释掉了treeItem上的连接(顺便说一下),我也没有成功。 I tried treeItemExpander.onclick = function () {...} to no avail as well.我试过treeItemExpander.onclick = function () {...}也无济于事。 The only thing that worked, but makes no sense in a widget was treeItemExpander.setAttribute("onClick", "alert('test');");唯一有效但在小部件中没有意义的是treeItemExpander.setAttribute("onClick", "alert('test');"); . .

Edit : I made a fiddle with the issue: http://jsfiddle.net/YCJ6X/编辑:我解决了这个问题: http : //jsfiddle.net/YCJ6X/

Edit : jovica (at the dojo-IRC) found out that the problem does not occur in Chrome on ubuntu.编辑:jovica(在 dojo-IRC)发现该问题在 ubuntu 上的 Chrome 中不会发生。

So how do I get an event attached to that image?那么如何将事件附加到该图像?

Answered by beuss on the Dojo-IRC: beuss在 Dojo-IRC 上的回答:

Modifying innerHTML changes previously appended DOM nodes as well.修改innerHTML也会更改先前附加的 DOM 节点。 Appending a text node instead of writing the text directly solves the issue.附加一个文本节点而不是直接写文本可以解决这个问题。

Updated fiddle: http://jsfiddle.net/YCJ6X/1/更新小提琴: http : //jsfiddle.net/YCJ6X/1/

Try to attach the event after you append the element.在附加元素后尝试附加事件。 I think that would solve your problem.我认为这会解决你的问题。

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

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