gpt4 book ai didi

javascript - Dojo 附加事件到动态创建的元素

转载 作者:行者123 更新时间:2023-11-30 08:17:03 28 4
gpt4 key购买 nike

我有一个表格。我包括道场。一切正常。我使用 Dojo 根据用户输入更改输入元素的类、值和属性(有点像验证)。

问题是,由于 IE,如果我想将输入的“类型”从“文本”更改为“密码”,我需要创建一个新的输入元素(我知道)。

一旦我创建了这个元素(它具有所有相同的属性和相同的 id)作为它所替换的元素,我的 Dojo 功能如 ...

dojo.query("#password2")
.connect("onclick",function(){
// if password2 is equal to the default text
if( this.value == "Confirm your password" ){
this.value = "";
UpdateType( this ); // this is the function that dynamically creates the new input element to have a type of 'password'
}
dojo.query("#list_password2").removeClass("error");
});

... 不再对新创建的元素起作用。我以前遇到过这个问题并且曾经使用 jQuery 并且有一个 livequery 插件将事件重新分配给元素。 Dojo 是否有我不知道的插件或 native 功能来执行此操作?

最佳答案

谷歌的第一个结果是这个答案,而且它没有提供最新的回复,这很奇怪。

无论如何,对于那些需要将事件附加到动态创建的元素的人,从 dojo 1.7 开始,可以使用事件委托(delegate)。一个简单的例子是:

require(["dojo/on", "dojo/query"], function(on) { 
on(parentElement, '.child-selector:click', function(e) {
alert('clicked');
});
});

我相信这段代码是不言自明的,所以我不会详细介绍。但是,关于事件委托(delegate)有一些值得注意的地方:

Note that event delegation will only work on events that bubble. Most DOM events do bubble, but there are a few exceptions. The mouseenter and mouseleave events do not bubble, but mouseover and mouseout are the bubbling counterparts. The focus and blur events do not bubble, but dojo/on normalizes focusin and focusout as bubbling equivalents. Also, scroll events don't bubble.

当然,不要忘记先加载dojo/query...

Note that dojo/query must be loaded for event delegation to work.

Read more如需进一步说明...希望对您有所帮助!

关于javascript - Dojo 附加事件到动态创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1629155/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com