是否可以对 javascript 变量进行更改事件?
我声明一个变量,它通过选择框中的另一个事件获取它的值。由于有不同的事件会更改变量(将其命名为 z
),因此我希望在变量更改时收到通知。
所以我的问题是:当变量发生更改时获取通知的最佳方式是什么? z.change(function(){});
抛出错误。
有没有办法在没有隐藏输入字段或其他类似帮助器的情况下做到这一点?
I declare a variable which gets it's value through another event out of a select-box. Since there are different events which change the variable (lets name it z
), I want to get informed when the variable gets changed.
So my question is: What is the best way to get informed when a variable gets changed?z.change(function(){});
throws an error.
Are there ways to do this without a hidden input-field or other helpers like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这实际上是不可能的,但有些浏览器支持 getter 和 setter,使用它们您可以实现在值出现时调用外部函数的东西。如果您希望它在所有浏览器中工作,那么您可以采用老式的方法来执行此操作:
然后始终记住仅通过这些函数访问该属性。
It's not really possible, but some browsers support getters and setters, and with them you could implement something that called an external function when the value is chanced. If you want this to work in all browsers, then you could go the old fashioned way of doing this:
And then always remember to only access the property through these functions.
您应该对 http://plugins.jquery.com/project/watch 感兴趣,但它不是与 SpiderMonkey 的方法一样完整,但确实有效。
You should be interested in http://plugins.jquery.com/project/watch which is not as complete as SpiderMonkey's method, but actually works.
试试这个:
我用这个方法写了一个双向模型视图绑定jquery插件jQueryMV https://github.com/gonnavis/jQueryMV 。
try this:
I use this method wrote a bidirectional model view binding jquery plugin jQueryMV https://github.com/gonnavis/jQueryMV .