首页 > 解决方案 > Is there an error in my code or have I simply written it wrong?

问题描述

I'm making a code where if you press the button after the name it will move to the other list. Pressing a button give me the error: "missing ) after argument list". I can't seem to find anything wrong in the code.

<!DOCTYPE html>
<html>
    <title>Favoritter</title>
    <body>
        <p>Hotell</p>
        <p id="hotellDiv"></p>
        <p>Favoritter</p>
        <p id="favDiv"></p>
    </body>
    <script>
        let hotelliste = ["Norwegian Wild", "Stofjord Hotel", "Norefjell Ski og Spa", "Brikdalsbre Fjellstove", "Gudvangen Fjordtell"];
        let favoritter = [];
        skrivhliste();
        skrivfliste();
        
        function skrivhliste(){
            document.getElementById("hotellDiv").innerHTML = "";
            for (var j = 0; j < hotelliste.length; j++){
                document.getElementById("hotellDiv").innerHTML += hotelliste[j] + "<input type=\"button\" onclick=\"leggTil("+hotelliste[j]+")\"><br>";
            }
        }
        function skrivfliste(){
            document.getElementById("favDiv").innerHTML = "";
            for (var j = 0; j < favoritter.length; j++){
                document.getElementById("favDiv").innerHTML += favoritter[j] + "<input type=\"button\" onclick=\"fjern("+favoritter[j]+")\"><br>";
            }
        }
        
        function leggTil(hotell){
            if (hotelliste.indexOf(hotell) > -1) {
                hotelliste.splice(hotelliste.indexOf(hotell), 1);
            }
            favoritter.push(hotell);
            skrivhliste();
        }
        function fjern(hotell){
            if (favoritter.indexOf(hotell) > -1) {
                favoritter.splice(favoritter.indexOf(hotell), 1);
            }
            hotelliste.push(hotell);
            skrivfliste();
        }
    </script>
</html>

标签: javascripthtml

解决方案


看这个:

"<input type=\"button\" onclick=\"fjern("+favoritter[j]+")\">

当您插入 的值时,您最终会得到什么字符串favoritter[j]

 <input type="button" onclick="fjern(Norwegian Wild)">

在那里你没有 string "Norwegian Wild",你有变量Norwegian后跟一个空格,然后是变量Wild(并且这些变量都不存在)。

如果您以编程方式生成 JavaScript,那么您需要生成围绕您生成的字符串的引号。

这很难做好。尤其是当 JS 嵌入到您也在动态生成的 HTML 中时。您有多个级别的转义序列要处理。

避免生成这样的字符串。请改用直接 DOM 方法。

例如:

一次,因此可以重复使用:

function clickHandler(event) {
    const button = event.currentTarget;
    const hotel = button.dataset.hotel;
    leggTil(hotel);
}

然后在你的循环中:

const button = document.createElement('input');
button.type = 'button';
button.value = 'display label';
button.dataset.hotel = hotelliste[j];
button.addEventListener('click', clickHandler);
document.getElementById("hotellDiv").appendChild(button);

推荐阅读