如何在JavaScript代码中放置HTML按钮?以下是我的代码,它在javascript代码中创建表并将其分配给HTML div。
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
$(document).ready(function()
{
var tablecontents = "";
tablecontents = "<table>";
for(var i=1;i<=10;i++)
{
tablecontents += "<tr>";
tablecontents += "<td>" + i + "</td>";
tablecontents += "</tr>";
}
tablecontents += "</table>";
document.getElementById("myTable").innerHTML = tablecontents;
}
});
</script>
</head>
<body>
<div id="myTable"></div>
</body>
</html>
上面的代码工作正常,并为我创建一个包含10行(每行一列)的表。现在我想在每一行中再创建一列,其中包含以下按钮
<button type="button"
id="myButton"
onclick="myButtonClicked()"
class="myButton">Click ME
</button>
我试过这个
tablecontents += "<td>
<button type="button"
id="myButton"
onclick="myButtonClicked()"
class="myButton">Click ME
</button>
</td>";
但由于语法错误或其他原因,我的HTML表单上没有出现任何内容。我想我在引号等方面犯了一些错误。
答案 0 :(得分:2)
每个按钮都应该有唯一的ID,
这是解决方案
for(var i=1;i<=10;i++){
tablecontents += "<tr>";
tablecontents += "<td>" + i + "</td>";
tablecontents += "<td>";
tablecontents += "<button type='button'";
tablecontents += "id='myButton"+i+"'";
tablecontents += "onclick='myButtonClicked()'";
tablecontents += "class='myButton'>Click ME";
tablecontents += "</button></td>";
tablecontents += "</tr>";
}
<强>已更新强>
当你的dom准备就绪时,将上面的代码和函数myButtonClicked
放在上面,你可以把它放在body标签之后
</body>
//put your scripts after body tag
<script>
//...above code
function myButtonClicked(){
alert("I am clicked")
}
</script>
答案 1 :(得分:1)
试试这个
tablecontents += '<td>
<button type="button"
id="myButton"
onclick="myButtonClicked()"
class="myButton">Click ME
</button>
</td>';
答案 2 :(得分:1)
问题在于当你执行"<button type="button[...]
时,类型之后的引号会结束字符串文字,因此js解析器会尝试查找名为button的变量,该变量不存在。即使确实存在,引擎也不知道如何处理它。
你可以在开发者控制台中看到错误(Chrome / Opera中的F12。我认为它是IE中的F10,不过对Mozilla不确定)。
一种解决方案是使用斜杠转义引号,如下:
tablecontents += "<td>
<button type=\"button\"
id=\"myButton\"
onclick=\"myButtonClicked()\"
class=\"myButton\">Click ME
</button>
</td>";
另一种是使用不同类型的引号(单引号/双引号):
tablecontents += '<td>
<button type="button"
id="myButton"
onclick="myButtonClicked()"
class="myButton">Click ME
</button>
</td>';
在JavaScript中,单引号和双引号的工作方式相同,但不可互换。