Javascript:检查元素是否已更改 [英] Javascript: Check if Element has Changed

查看:77
本文介绍了Javascript:检查元素是否已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果有可能,如果元素已更改或其属性如何检查javascript?

I want to know, if it's possible, how to check in javascript if an element has changed or an attribute of it?

我的意思是像 window.onhashchange 对于以下元素:

I mean something like window.onhashchange for an element something like:

document.getElementById("element").onElementChange = function();

据我所知 onchange 是这样的,但如果我想以这种方式知道它会起作用:

As I know onchange is something like this, but will it work if I want to know in this way:

var element = {};
element.attribute = result;

element.attribute.onchange = function();


推荐答案

据我了解你想要onChange对javascript对象属性。答案是否定的,据我所知,它并不存在。

As far as I understand you want onChange on javascript object Properties. The answer is no, it doesn't exist as far as I know.

但你可以制作一个这样的setter函数(作为概念证明):

But you can make a setter function like this (As a proof of concept):

var element = {};

element.setProperty = function(property, value) {
  if (typeof(element.onChange) === 'function') {
    element.onChange(property, element[property], value);
  }

  element[property] = value;
};



element.onChange = function(property, oldValue, newValue) {
  alert(property + ' changed from ' + oldValue + ' to ' + newValue);
};

element.setProperty('something', 'Hello world!');

现在你得到一个警告框,里面有'从undefined更改为Hello World!'。并且(element.something ==='Hello World!')将返回 true

now you get an alert box with 'something changed from undefined to Hello World!'. And (element.something === 'Hello World!') will return true.

如果你现在打电话:

element.setProperty('something', 'Goodbye world!');

你会得到一个警告框,其中包含'来自Hello World的更改内容!再见世界!'。

you get an alert box with 'something changed from Hello World! to Goodbye World!'.

当然,您必须通过 setProperty 方法设置属性如果你想捕获这个事件你的代码!

Off course you have to set the property only via the setProperty method in all of your code if you want to capture this event!

编辑:

At将来的某个时候,您可以使用 Object.observe()

At some time in the future, you might be able to use Object.observe().

编辑2:

现在还有代理

这篇关于Javascript:检查元素是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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