Javascript-如何在选择框附加选项时进行监听?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Javascript-如何在选择框附加选项时进行监听?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2297字,纯文字阅读大概需要4分钟。
内容图文
我有一个选择框,我想知道另一个js函数何时向其添加一个选项.发生这种情况时会触发任何事件吗?
$('select').append('<option>Option 3</option>');
$('select').on('option_appended', function() {
console.log('Option appended to select box');
});
更改无效:
http://jsfiddle.net/CuQjV/
解决方法:
最新的方法是Mutation Observers,但支持范围并不广泛,较旧的已过时的方法是Mutation Events,可靠性不高,有些是profoundly degrade the performance of the DOM.您可以执行此操作.
Avoid DOM mutation event listeners
Adding DOM mutation listeners to a document disables most DOM
modification optimizations and profoundly degrades the performance of
further DOM modifications to that document. Moreover, removing the
listeners does not reverse the damage. For the reason, the following
events should be avoided wherever possible: DOMAttrModified,
DOMAttributeNameChanged, DOMCharacterDataModified,
DOMElementNameChanged, DOMNodeInserted, DOMNodeInsertedIntoDocument,
DOMNodeRemoved, DOMNodeRemovedFromDocument, DOMSubtreeModified
的HTML
<select id="watch">
<option>Option 1</option>
<option>Option 2</option>
</select>
<button id="add">Add</button>
Java脚本
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
(function () {
"use strict";
if (typeof window.MutationObserver !== "function") {
window.MutationObserver = window.WebKitMutationObserver || window.MozMutationObserver;
}
var watch = document.getElementById("watch");
function whenClicked() {
var option = document.createElement("option");
option.appendChild(document.createTextNode("Option" + Date.now()));
watch.appendChild(option);
}
document.getElementById("add").addEventListener("click", whenClicked, false);
if (typeof window.MutationObserver !== "function") {
watch.addEventListener("DOMNodeInserted", function (evt) {
console.log("New element detected", evt.target);
}, false);
} else {
var observer = new window.MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList') {
console.log("New element detected", mutation.addedNodes[0]);
}
});
});
observer.observe(watch, {
childList: true,
characterData: true,
subtree: true
});
}
}());
注意:在本示例中,我也使用了addEventListener,它也不是跨浏览器,请搜索addevent来查找跨浏览器功能.或使用给定的MDN页面上的一个.我还使用了ECMA5方法Array.prototype.forEach,但是有垫片,或者可以使用for或while重写.
内容总结
以上是互联网集市为您收集整理的Javascript-如何在选择框附加选项时进行监听?全部内容,希望文章能够帮你解决Javascript-如何在选择框附加选项时进行监听?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。