我有这段代码
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,但下面的注释行在运行代码时效果很好。
答案 0 :(得分: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');