哇,你近了。编辑评论:
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = type; // Really? You want the default value to be the type string?
element.name = type; // And the name too?
element.onclick = function() { // Note this is a function
alert("blabla");
};
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
document.getElementById("btnAdd").onclick = function() {
add("text");
};
<input type="button" id="btnAdd" value="Add Text Field">
<p id="fooBar">Fields:</p>
现在,onclick
您可以考虑使用addEventListener
(在大多数浏览器上)或attachEvent
(在除最近的Microsoft浏览器之外的所有其他浏览器上)使用设置元素的属性(称为“ DOM0事件处理”),而不是设置元素的属性-您必须检测并处理两种情况-这种形式的“ DOM2事件处理”具有更大的灵活性。但是,如果您不需要多个处理程序,则可以使用旧的DOM0方法。
与上述内容分开:您可以考虑使用优质的JavaScript库,例如jQuery,Prototype,YUI,Closure或[其他几种。它们可以平滑浏览器之间的差异,例如addEventListener
/attachEvent
,提供有用的实用程序功能以及其他各种功能。显然,没有库是无法做的,没有库,因为库只是JavaScript代码。但是,当你使用一个好的图书馆有广泛的用户基础,你得到的好处巨大已经被其他人处理这些浏览器的差异,等完成的工作数量