答案 0 :(得分:0)
这是因为trigger
方法接受数组或对象,并且它试图将allChangedInputs[i].input
转换为数组。
只需将其转换为
[allChangedInputs[i].input]
解决您的问题,请参阅下面的演示
var onInputMounted = function(e, data) {
console.log("mounted", data);
};
var onInputUnmounted = function(e, data) {
console.log("unmounted", data);
};
var observer = new MutationObserver(function(changes) {
changes.forEach(function(element, index) {
var allChangedNodes = [];
var allChangedInputs = [];
if (element.type === "childList") {
// get all changed (added/removed) HTML nodes
if (element.addedNodes.length > 0) {
allChangedNodes = Array.prototype.slice
.call(element.addedNodes)
.map(function(e, i) {
return {
node: e,
event: "mounted"
};
});
} else if (element.removedNodes.length > 0) {
allChangedNodes = Array.prototype.slice
.call(element.removedNodes)
.map(function(e, i) {
return {
node: e,
event: "unmounted"
};
});
}
// get all changed (added/removed) HTML :input fields
allChangedInputs = allChangedNodes
.map(function(e) {
return $(e.node)
.find(":input")
.addBack(":input")
.map(function(i, input) {
return {
input: input,
event: e.event
};
});
})
.reduce(function(arrLike1, arrLike2) {
var arr1 = Array.prototype.slice.call(arrLike1);
var arr2 = Array.prototype.slice.call(arrLike2);
return arr1.concat(arr2);
});
}
// trigger the corresponding event: mounted (for added inputs), unmounted (for removed ones)
for (var i = 0; i < allChangedInputs.length; i++) {
console.log("trigger", allChangedInputs[i]);
$("#container").trigger(
allChangedInputs[i].event,
[allChangedInputs[i].input] //this line
);
}
});
});
// register events
$("#container").on("mounted", onInputMounted);
$("#container").on("unmounted", onInputUnmounted);
// observe changes on DOM
observer.observe($("#container")[0], {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
// append a div with two inputs
$("#container").append(
'<div><input id="name" /><select id="gender"><option value="male">male</option><option value="female">female</option></select></div>'
);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
&#13;