如何检测DOM属性的变化? [英] How to detect change in a property of DOM?

查看:160
本文介绍了如何检测DOM属性的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在选择框中更改项目时,DOM的属性似乎已更改。
因此,我在下面进行了编码:

When I change item in selectbox, a property of DOM seems changed. So I coded below:

<select id="hoge">
<option value="0">hoge</option>
<option value="1">piyo</option>
</select>

<script>
var hoge = document.getElementById("hoge").addEventListener("change", func, false);
document.getElementById("hoge").value = 1; // <- (1)

function func(e) {
alert("Detected!");
}
</script>

在这种情况下,当我在selectbox中更改项目时,将调用func。但是,当调用(1)时,不会调用func。
更改事件似乎只检测到用户提交的内容。

In this case, when I change item in selectbox, func is called. But when (1) is called, func is not called. Change event seems to detect only committed by the user.

所以我尝试了MutationObserver。

So I tried MutationObserver.

<select id="hoge">
<option value="0">hoge</option>
<option value="1">piyo</option>
</select>

<script>
var hoge = new MutationObserver(function(mutations) {
alert("Detected!");
});
hoge.observe(document.getElementById("hoge"), { attributes: true, subtree: true });
document.getElementById("hoge").options[1].setAttribute("selected", "selected"); // <- (1)

</script>

在这种情况下,当调用(1)时,将调用func。但是当我在选择框中更改项目时,不会调用func。
MutationObserver似乎只检测属性。

In this case, when (1) is called, func is called. But when I change item in selectbox, func is not called. MutationObserver seems to detect only attributes.

无论哪种情况,我都想调用func。
如何通过脚本检测DOM属性的变化?

I want to call func in either case. How to I detect change in a property of DOM by script?

推荐答案

我认为有两种方法可以尝试:

第一个是手动处理on change事件,而不考虑事件冒泡或传播,然后在更改元素的值后立即调用 onchange 。像这样:

I think there are 2 ways you can try:
1st is manually handle the on change event, without considering event bubble or propagation, then call onchange right after you change the value of element. Like this:

var myEle = document.getElementById("hoge");
myEle.value = 1; // <- (1)
myEle.onchange()

第二个是它自然就像浏览器一样工作,然后尝试在该元素上创建和分发事件。像这样:

2nd is to make it naturally like browsers work, then try to create and dispatch event on that element. Like this:

if ("createEvent" in document) {
    var event = document.createEvent("HTMLEvents");
    event.initEvent("change", false, true);
    myEle.dispatchEvent(event);
} else
    myEle.fireEvent("onchange");

这篇关于如何检测DOM属性的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆