简体   繁体   中英

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() )

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.

See a demo of the above working here; http://jsfiddle.net/sskKc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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