在innerHTML中的getElementById中获取一个带引号的字符串变量

get a string variable with quotation marks in getElementById inside a innerHTML

本文关键字:一个 变量 字符串 getElementById 中的 innerHTML 获取      更新时间:2023-09-26

我正在尝试获取一个带有数量id的值。这段代码是用JavaScript编写的,当它运行时,id数量中的报价是这样的"quantity',我认为这就是问题所在。有人能建议用什么来获得像这样的"quantity" 的id吗

tab.innerHTML += "<input  type='button' onclick='AddtoCart(document.getElementById('quantity').value;);' />";

您需要转义引号。类似:

tab.innerHTML += "<input  type='button' onclick='AddtoCart(document.getElementById('"quantity'").value;);' />";

我建议不要使用内联JavaScript。正如你已经看到的,它给你带来了麻烦。这只会在未来给你带来更多的麻烦。

相反,让你的按钮像这样:

tab.innerHTML += "<input type='button' class='addToCart' />";

然后在代码的其他地方:

tab.addEventListener('click', function(e){
    var classes = e.target.className.split(' ');
    if(classes.indexOf('addToCart') >= 0){
        AddtoCart(document.getElementById('quantity').value);
    }
});

这类似于jQuery处理"委派"事件的方式。