javascript - 如何将变量传递给 .innerHTML

标签 javascript

我正在尝试使用参数将变量放入 .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/

相关文章:

javascript - Emberjs 从 ArrayController 填充 Ember 下拉框

javascript - 使用 Ajax Get 方法将数据显示到特定元素

javascript - help : when calling a javascript functions, 它被jquery的onready方法中断了!

javascript - 如何消除 Magento 1.8 中的 jQuery 冲突

javascript - 这个 CSS 菜单是如何创建的?

javascript - RSA私钥无法解密数据

javascript - 从字符串的开头和结尾 trim 空格

javascript - 深入React useEffect/useEffect的使用?

javascript - 计算表中的行数,如果大于 0,则显示表

javascript - 如何在 Google Maps InfoWindow 中为多个位置实现分页?