javascript - 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>
解决方案
看这个:
"<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);
推荐阅读
- c# - KeyVaultClient.AuthenticationCallback 不触发
- python - 将数据拟合到高斯轮廓时如何在 lmfit 中包含误差线?
- image-processing - 什么是图像字幕以及它如何在视觉问答中使用?
- javascript - 输入验证未检测到空值
- cloudkit - 在 CloudKit 仪表板中访问来自不同 AppleID 的记录
- arrays - 如果最后一个子数组的大小与其他子数组不同,则将 each_slice 合并到子数组中并设置默认元素值
- spring-boot - 简化 Spring Boot 应用程序的 docker 构建和部署过程
- reactjs - 在 MobX 中更改可观察值时重新渲染组件
- c# - 从 Wpf 中的资源中的 CodeBehind 设置 FontFamily
- java - 使用 Selenium 自动化聊天机器人时如何从最新的聊天气泡中获取文本