如何在设置元素的innerHTML
时使用javascript变量?要查看我的问题,请先点击CLICK 1
。这将显示delete
,然后点击delete
。为什么警报不显示111-aaaa,1
?我怎么能这样做?
https://jsfiddle.net/brf75wvp/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="test_id" value="1"/>
<div onclick="test_fn1()">CLICK 1</div>
<div id="demo"></div>
<script>
function test_fn1() {
var test_id_val = document.getElementById("test_id").value;
document.getElementById("demo").innerHTML = "<span onclick= delete_fn('111-aaaa, test_id_val')>delete</span>";
};
</script>
<script>
function delete_fn(no_delete) {
alert(no_delete);
};
</script>
答案 0 :(得分:2)
您应该使用如下的字符串添加变量。
function test_fn1() {
var test_id_val = document.getElementById("test_id").value;
document.getElementById("demo").innerHTML = "<span onclick=delete_fn('111-aaaa,"+test_id_val+"')>delete</span>";
}
答案 1 :(得分:1)
您需要将变量连接到字符串:
document.getElementById("demo").innerHTML = "<span onclick=delete_fn('111-aaaa," + test_id_val + "')>delete</span>";
答案 2 :(得分:1)
存在语法错误。正确的是:
document.getElementById("demo").innerHTML = "<span onclick=delete_fn('111-aaaa," + test_id_val + "')>delete</span>";
答案 3 :(得分:0)
您的代码有一些错误尝试使用下面这将工作
<script>
function test_fn1() {
var test_id_val = document.getElementById("test_id").value;
document.getElementById("demo").innerHTML = '<span onclick=delete_fn("111-aaaa,'+test_id_val+'")>delete</span>';
};
</script>