我希望不断地(因为内容是通过AJAX接收的)检查是否存在一个类名为email的输入,如果存在,则显示另一个类名为upload的输入,如果该输入存在,则单击另一个类名为button的输入以执行某些操作。
我设法不断地检查带有email类名的输入是否存在,以及是否存在带有upload类名的输入,但我不知道如何继续。
这是我到目前为止所知道的:
(function(doc,found) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var mydiv = doc.querySelector("input.email");
if(found && !mydiv){
// Was there but is gone, do something
found = false;
$('input.upload').hide();
}
if(mydiv){
// Found it, do something
found = true;
$('input.upload').show();
}
});
});
observer.observe(doc, { childList: true, subtree: true });
})(document,false);发布于 2016-05-26 04:44:31
您正在使用jQuery,但也在使用document.querySelector()。最好保持一致并始终使用jQuery,或者只直接使用DOM方法而不使用jQuery。
通过使用.toggle(),可以使显示/隐藏的代码更加简洁。
(function(doc) {
var observer = new MutationObserver(function(mutations) {
// You don't need to iterate over the mutations,
// and showing/hiding the upload input can be done with a one-liner:
$('input.upload').toggle($("input.email").length>0);
});
observer.observe(doc, { childList: true, subtree: true });
// Here is the click handler. It checks for the existence of the input.
$('input.button').click(function() {
if ($('input.email').length) {
alert('There is an email input. We could do something.');
} else {
alert('No email input present');
}
});
})(document);
// Simulate a mutation that removes/adds an `input.email` control on button click
$('#toggle').click(function() {
if ($('input.email').length) {
$('input.email').remove();
} else {
$('<input class="email" type="text">').insertBefore($('br')[0]);
}
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Email: <input class="email" type="text"><br>
Upload: <input class="upload" type="file"><br>
<input class="button" type="button" value="button"><br>
<hr>
Click this button to trigger a mutation concerning email input:<br>
<button id="toggle">Create/Delete email input</button>
关于MutationObserver的警告
在侦听MutationObserver事件时必须小心。如果您在事件处理程序中进行了另一次更改,则会触发一个新事件,并且您可能会陷入无限循环。
即使是上面的代码也有风险:toggle方法将更改元素的可见性,jQuery将通过设置display CSS样式来实现这一点。但这是对文档的修改!因此会触发另一个突变事件,并再次调用toggle方法。幸运的是,当jQuery发现可见性已经正确设置时,它不会更改文档--第二次调用就是这种情况--因此不会触发进一步的突变事件。
https://stackoverflow.com/questions/37446804
复制相似问题