2013-12-19 119 views
2

我有這樣的代碼無法更改對象變量的innerHTML

var errorId = { 
     name : document.getElementById('para_name').innerHTML, 
     desc : document.getElementById('para_desc').innerHTML, 
     photo : document.getElementById('para_photo').innerHTML, 
     price : document.getElementById('para_price').innerHTML, 
     cat  : document.getElementById('para_cat').innerHTML 
    }; 
    errorId.name = 'Hello There'; 
    // this works: document.getElementById('para_name').innerHTML = 'Hello'; 

,當我嘗試使用對象訪問改變innerHTML的「」但是我無法更改innerHTML,但是在運行代碼時,下面的註釋行完美工作。

回答

5

訪問innerHTML未設置對元素的引用,而是僅返回其html的字符串表示形式。所以,你可以做,而不是:

var errorId = { 
    name : document.getElementById('para_name'), 
    desc : document.getElementById('para_desc'), 
    ... 
}; 
errorId.name.innerHTML = 'Hello There'; 

或者你也許可以這樣做:

var errorId = { 
    _name : document.getElementById('para_name'), 
    _desc : document.getElementById('para_desc'), 
    _photo : document.getElementById('para_photo'), 
    ... 
    name : function(value){ 
     if(this._name) 
      this._name.innerHTML = value; 
    } 
    ... 

}; 
errorId.name('Hello There'); 
+0

很好,謝謝:) – user3105607

+1

@ user3105607歡迎您.. – PSL