我正在尝试使用参数将变量放入 .innerHTML。然而,每当我试图传递一些东西时,它往往会给我一个错误,因为它试图找到一个不存在的项目的 innerHTML。我希望内部 HTML 可以针对多种不同的功能进行自定义。
function roll(type, num, type2){
var total = (Math.floor(Math.random()*type)+1)
var total2 = total * num;
type2.innerHTML = total2;
}
d20button.onclick = function(){
roll(19,1, 'd20p');
}
所以我的想法是,当我使用不同的 onclick 按钮时,我可以根据用户输入的内容传入不同的变量。但是,它没有使用 d20p.innerHTML,而是继续使用 type2.innerHTML。我想知道是否有一种方法可以让它使用 d20p.innerHTML,同时也让它为其他选项打开。
最佳答案
'd20p'
是在 roll
中作为 type2
传递的字符串。字符串没有任何名为 innerHTML
的属性,因此您应该在访问 innerHTML
document.getElementById()
function roll(type, num, type2){
var total = (Math.floor(Math.random()*type)+1)
var total2 = total * num;
document.getElementById(type2).innerHTML = total2;
}
如果你想改变点击的任何按钮的 innerHTML
那么你可以将 this
作为 onclick
事件的参数传递,它将引用单击按钮。
d20button.onclick = function(){
roll(19,1,this);
}
function roll(type, num, type2){
var total = (Math.floor(Math.random()*type)+1)
var total2 = total * num;
type2.innerHTML = total2;
}
关于javascript - 如何将变量传递给 .innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840566/