问题描述
有几个问题要求使用jQuery将元素更改为其他类型之一,保留属性。 .replaceWith()
做的伎俩,这就是使用。但是从DOM中删除原始元素会丢弃它的事件处理程序。如何更换元素并将任何绑定的处理程序转移到新元素?
There are a few questions that ask about changing an element to one of another type, preserving attributes, using jQuery. .replaceWith()
does the trick, and that's what this plugin uses. But dropping the original element from the DOM drops its event handlers with it. How would one go about replacing an element and transferring any bound handlers to the new element?
具体来说,我正在替换一个<输入类型=text>
与< select>
。我正在使用jQuery 1.10。
Specifically, I'm replacing an <input type="text">
with a <select>
. I'm using jQuery 1.10.
推荐答案
我发现另一个似乎回答你想要做的事情的问题
I found another question that seems to answer what you're trying to do
他们执行以下
$.each($._data($('#original').get(0), 'events'), function() {
// iterate registered handler of original
$.each(this, function() {
$('#target').bind(this.type, this.handler);
});
});
访问原始的 $ ._ data
元素 $('#original')
允许您访问其附加的事件,因此迭代每个元素允许您将相同的事件附加到新元素,在这种情况下 $('#target')
Accessing the $._data
of the original element $('#original')
allows you to gain access to the events it has attached, so iterating over each one allows you to attach the same events to a new element, in this case $('#target')
这篇关于更改元素类型,保留jQuery事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!