是否有统一的方法将`innerHTML`和`onclick`设置为一个元素?

时间:2015-10-12 01:43:09

标签: javascript html html5

我尝试使用其JSON描述创建元素。 JavaScript现在提供了这个:

elem.innerHTML = "Text"; // works fine
elem.onclick = "alert(true)"; // doesn't work

elem.setAttribute("innerHTML", "Text"); // doesn't work
elem.setAttribute("onclick", "alert(true)"); // works fine

不幸的是,我不允许打印

elem.onclick = function() {alert(true)};

是否有统一的方法将innerHTMLonclick设置为一个元素? 像这样:

var props = {"innerHTML":"Text", "onclick":"alert(true)"};
var elem = document.createElement("BUTTON");

for (property in props) elem[property] = props[property];
/* or */
for (property in props) elem.setAttribute(property, props[property]); 
/* or maybe something else */

1 个答案:

答案 0 :(得分:1)

你冷使用Function构造函数:

elem.onclick = new Function('', 'return alert(true);');

See working Fiddle

编辑:我找不到对元素上的事件和属性执行此操作的统一方法,但由于所有事件都以on关键字开头,因此您可以检查它是否为for循环中的事件或属性:

for (property in props) {
    if(property.substr(0,2) === 'on') {
        //an event
        elem.setAttribute(property, props[property]); 
    }
    else {
        //an attribute
        elem[property] = props[property];
    }
}

See working Fiddle