jQuery - 检测布尔值的变化

时间:2012-03-11 16:34:29

标签: javascript jquery boolean detect

有没有办法通过jQuery检测全局布尔值是否从false变为true?

3 个答案:

答案 0 :(得分:8)

是的,使用一个getter / setter对,其中setter捕获变量的设置:http://jsfiddle.net/M768B/

(function() {
    var val = false;

    ​Object.defineProperty(window, "something", {
        get: function() {
            return val;
        },
        set: function(v) {
            val = !!v; // `!!` to force setting a boolean
            alert("Changed to " + val);
        }​​
    });
})();

答案 1 :(得分:0)

解决方案可能是

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript Object - watch () method example</title>
</head>
<body>
<h1 style="color: red">JavaScript Object : watch() method</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[ o = {x:10}
o.watch("x",
function (id,oldvalue,newvalue) {
document.writeln("o." + id + " changed from "
+ oldvalue + " to " + newvalue+"<br />")
return newvalue
})
o.x = 20
o.x = 30
o.x = 40
//]]>
</script>
</body>
</html> 

兼容:

  • Internet Explorer 7
  • Firefox 3.6
  • Google Chrome 7
  • Safari 5.0.1
  • Opera 10

here

答案 2 :(得分:0)

将一组函数回调保存为“观察者”。当任何东西通过你的接口函数改变布尔值(例如setBooleanValue(True);)然后遍历回调数组并调用每个函数来通知观察者。

相关问题