I have an input element in my contenteditable <div>
, sample code:
我在contenteditable
<div class="ucclass" contenteditable="true">
<input id="abc" class="js_xxx">
</div>
I have a piece of code which used to paste an input with auto generated id into the <div>
.
我有一段代码用于将带有自动生成的id的输入粘贴到
How can I grab the input id when I delete it?
删除时如何获取输入ID?
Any help will be appreciated.
任何帮助将不胜感激。
2 个解决方案
#1
You could use a MutationObserver
to achieve this. To track any sort of node removed from your contenteditable
element, observe the following example
您可以使用MutationObserver来实现此目的。要跟踪从您的contenteditable元素中删除的任何类型的节点,请遵循以下示例
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//console.log($(mutation.removedNodes)); // <<-- includes text nodes as well
$(mutation.removedNodes).each(function(value, index) {
if(this.nodeType === 1) {
console.log(this.id) // abc
}
});
});
});
var config = { attributes: true, childList: true, characterData: true };
observer.observe($('.ucclass')[0], config);
JSFiddle Link
#2
MutationObserver is perfect if you don't need pre-IE11 support.
如果您不需要IE11之前的支持,MutationObserver是完美的。
Otherwise, you could listen for a keydown
event on .ucclass
, collect all of its descendants with ids, and set a timer that checks if any element has been deleted:
否则,你可以在.ucclass上监听keydown事件,使用id收集它的所有后代,并设置一个计时器来检查是否有任何元素被删除:
$('.ucclass').on('keydown', function(e) {
var ids= $(this).find('[id]'),
self= $(this);
setTimeout(function() {
ids.each(function() {
if(!self.find('#'+this.id).length) {
//do something
}
});
});
});
#1
You could use a MutationObserver
to achieve this. To track any sort of node removed from your contenteditable
element, observe the following example
您可以使用MutationObserver来实现此目的。要跟踪从您的contenteditable元素中删除的任何类型的节点,请遵循以下示例
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//console.log($(mutation.removedNodes)); // <<-- includes text nodes as well
$(mutation.removedNodes).each(function(value, index) {
if(this.nodeType === 1) {
console.log(this.id) // abc
}
});
});
});
var config = { attributes: true, childList: true, characterData: true };
observer.observe($('.ucclass')[0], config);
JSFiddle Link
#2
MutationObserver is perfect if you don't need pre-IE11 support.
如果您不需要IE11之前的支持,MutationObserver是完美的。
Otherwise, you could listen for a keydown
event on .ucclass
, collect all of its descendants with ids, and set a timer that checks if any element has been deleted:
否则,你可以在.ucclass上监听keydown事件,使用id收集它的所有后代,并设置一个计时器来检查是否有任何元素被删除:
$('.ucclass').on('keydown', function(e) {
var ids= $(this).find('[id]'),
self= $(this);
setTimeout(function() {
ids.each(function() {
if(!self.find('#'+this.id).length) {
//do something
}
});
});
});