如何使自定义对象支持jQuery change()等 [英] How can I make a custom object support jQuery change() etc
问题描述
我想创建一种新型的复合HTML输入.大概是这样
I want to create a new type of composite HTML input. Roughly like this
function create_node ()
{
let node = document.createElement ('span');
let a = document.createElement ('input');
let b = document.createElement ('input');
node.appendChild (a);
node.appendChild (b);
node.value = '';
$(a) .change (function () { /* update node.value */ });
$(b) .change (function () { /* update node.value */ });
return node;
}
我希望能够编写这样的jQuery代码:
I want to be able to write jQuery code like this:
let foo = create_node ();
$(foo).change (function () { /* use foo.value */ });
在create_thing
中我该怎么办,这将使$(foo).change(...)
正常工作,例如,只要更改a
或b
,就会调用其回调(具有正确的this
上下文)?
What do I have to do in create_thing
which will make $(foo).change(...)
work properly, as in, its callback will be invoked (with the correct this
context) whenever a
or b
is changed?
推荐答案
因此,事实证明,由于input
节点已经具有change
事件,因此该事件默认在父节点中冒泡,因此您无需不必做任何事情.
So it turns out that because the input
nodes already have a change
event, that event bubbles up through parent nodes by default, so you don't have to do anything.
如果内部节点还没有change
事件,则可以执行以下操作
If the internal nodes don't already have a change
event, you can do things like this
$(internal_node) .click (function () {
// ...
$(parent_node) .change ();
});
您可以像这样取消默认更改事件
And you can suppress the default change events like this
$(internal_node) .click (function (e) {
e .preventDefault ();
e .stopPropagation ();
});
这篇关于如何使自定义对象支持jQuery change()等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!