简体   繁体   English

使用字符串方法更改Javascript对象中的DOM元素参数

[英]Using string methods to change DOM element parameters in Javascript Objects

If I have an object : 如果我有一个对象:

 function myClass(id) {
   this.em = document.getElementById(id);
   this.html = function(data) {
     this.em.html = data;
   }
 }

Now I can : 现在我能 :

  var em = new MyClass("id");
  em.html("NEW HTML HERE");

I need : 我需要 :

em.html = "NEW HTML HERE";

Is It possible? 可能吗?

In HTML5 you could define a set method on the html property (see defineProperty() ) 在HTML5中,您可以在html属性上定义set方法(请参见defineProperty()

function myClass(id) {
    this.em = document.getElementById(id);    

    Object.defineProperty(this, 'html', {
        set: function(val) {
            this.em.html = val;
        }
    });
}

... but this will only work in the most modern browsers ; ...但是只能在最现代的浏览器中使用 ; IE8, Chrome 5, Firefox 4. IE8,Chrome 5,Firefox 4。

See a demo of the above working here; 在此处查看上述示例。 http://jsfiddle.net/sskKc/ http://jsfiddle.net/sskKc/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM