我正在尝试创建一个简单的 html 页面和一些动态按钮。这就是我到目前为止所做的:
<HTML>
<BODY bgColor="#d4d4d4" onload="OnLoad()" >
<script language = "javascript">
function OnQuery()
{
alert("Query");
}
function OnLoad()
{
document.write("<INPUT onclick=\"OnQuery()\" type=\"button\" value=\" Search \" name=\"querybtn\" />");
}
</script>
</BODY>
</HTML>
正如你从代码中可以猜到的那样,我对 JavaScript 非常陌生。正在添加“搜索”按钮,但单击时不会调用 OnQuery
。我究竟做错了什么?这是一个简单的原型(prototype)代码,仅适用于 IE。
最佳答案
将 document.writes 更改为使用 document.createElement 来创建 Dom
function OnQuery()
{
alert("Query");
}
function OnLoad()
{
var Objs = new Array();
var xmlInput = "<QueryResult>Some values</QueryResult>";
var doc = xmldso.XMLDocument;
doc.loadXML(xmlInput );
var x = doc.getElementsByTagName("QueryResult");
for(i=0; i < x.length; ++i)
{
Objs[i] = new MyObject(x[i]);
}
//Create the table element
var table = document.createElement("table");
table.setAttribute("border",1);
for(i=0; i < Exams.length;++i)
{
//Create the row element
var row = document.createElement("tr");
//Create the 2 columns
var col1 = document.createElement("td");
var col2 = document.createElement("td");
//Create the checkbox input
var chkId = "Row" + i;
var chkIdInput = document.createElement("input");
chkIdInput.setAttribute("type","checkbox");
chkIdInput.id = chkId;
//Add the checkbox to the column
col1.appendChild(chkIdInput);
//Set the text of second column
col2.textContent = Objs[i].Prop1;
//Add columns to the row
row.appendChild(col1);
row.appendChild(col2);
//Add the row to the table
table.appendChild(row);
}
//Add the table to the body
document.body.appendChild(table);
//Create the search button
var searchBtn = document.createElement("input");
//Set the attributes
searchBtn.setAttribute("onclick","OnQuery()");
searchBtn.setAttribute("type","button");
searchBtn.setAttribute("value","Search");
searchBtn.setAttribute("name","querybtn");
searchBtn.style.marginLeft = "20px";
searchBtn.style.marginTop = "20px";
//Add the button to the body
document.body.appendChild(searchBtn);
}
function OnUnload()
{
}
在 IE 10 和 9 中的 jsfiddle 中工作未检查较低版本
关于javascript - 使用 JavaScript 动态添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18287564/