javascript - (未捕获的 SyntaxError:输入意外结束)
问题描述
大家好,
我是一个完全的编码初学者,当我收到错误时,我一直在与网络研讨会一起编码:Uncaught SyntaxError: Unexpected end of input。我附上了错误的屏幕截图。这发生在我添加 inputChange 函数时。网络研讨会的讲师没有任何错误,我的代码(到目前为止)与他在视频中的代码相同。
谁能帮我理解和解决这个问题?
这是我的代码:
//Variables, Arrays, and Objects, dotNotation, bracketNotation
//Dom manipulation
let items = [
{
name: 'Ironhack T',
price: 10,
image: 'https://miro.medium.com/max/5190/1*aVsUjp1zvlRb1799gDjbLA@2x.jpeg'
},
{
name: 'Ironhack Hoodie',
price: 15,
image: 'https://m.media-amazon.com/images/I/B1i3u9-Q-KS._AC_CLa%7C2140%2C2000%7CB1wqstnnTfS.png%7C0%2C0%2C2140%2C2000%2B0.0%2C0.0%2C2140.0%2C2000.0_UL1500_.png'
},
{
name: 'Ironhack Sticker',
price: 2,
image:'https://e7.pngegg.com/pngimages/887/803/png-clipart-ironhack-web-development-job-startup-company-design-blue-user-interface-design-thumbnail.png'
},
{
name: 'Ironhack Mug',
price: 8,
image: 'https://d0bb7f9bf11b5ad1a6b2-6175f06f5e3f64e15abbf67415a276ec.ssl.cf1.rackcdn.com/product-images/designlab/11-oz-traditional-ceramic-coffee-mugs-7102-white1582888132.jpg'
},
];
let list = document.querySelector('ul');
items.forEach((item, i) =>{
console.log(item.name);
list.innerHTML += `<li>
<div>Name: ${item.name}</div>
<div>Price: $${item.price}</div>
<img src="${item.image}" />
<input type='number' placeholder='quantity' onchange='inputChange(${i}, '${item.name}', '${item.price}')' />
<button>Buy item</button>
</li>`
});
function inputChange(i, name, price){
console.log('I want to buy the ',i,' item named, ',name,' that costs $',price);
};
*{
transition: all 1s;
}
body{
padding: 10px;
background-color: lightseagreen;
}
section{
display: flex;
flex-direction: row;
}
img {
width: 50px;
}
#cart{
background-color:salmon;
}
#cart, #items{
width: 50vw;
}
h1{
color:#7c32ff;
}
/*selecting a tag*/
p{
color:green;
text-decoration: line-through;
}
/*Ids have hashtags*/
#two {
background-color:rebeccapurple;
}
/*classes have dots*/
.example {
border: 5px dashed purple;
margin: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!--Now my CSS is linked to my html-->
<link href="/favicon.ico" type="image/x-icon" rel="icon" />
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<section>
<div>
<h2>Items</h2>
<ul id="items">
</ul>
</div>
<div>
<h2>Cart <span id="grandTotal">$0</span></h2>
<ul id="cart">
</ul>
</div>
</section>
<!-- <div class="example">
This is a div
</div>
<div class="example" id="two">
This is a div 2
</div>
<div class="example">
This is a div 3
</div>
<i>This will be italic text</i>
<b>This will be bold text</b>
<h1>This is a certain size</h1>
<p>This is for paragraphs</p> -->
<script src="./script.js"></script>
</body>
</html>
解决方案
编辑:修复以下代码中的单 (') 和双 (") 引号就足够了
注意包裹传递给 inputChange 的变量的双引号。并注意包裹传递给属性的完整值的单引号onchange='...'
// Inside the forEach loop
list.innerHTML += `<li>
<div>Name: ${item.name}</div>
<div>Price: $${item.price}</div>
<img src="${item.image}" />
<input type='number' placeholder='quantity' onchange='inputChange("${i}", "${item.name}", "${item.price}")' />
<button>Buy item</button>
</li>`;
编辑:另外记录输入的当前值的替代解决方案
在调试时,我采用了另一个解决方案,它还记录了输入元素的当前值(即客户想要购买多少)。
- 只为每个项目添加一个输入元素,并带有一个 id 属性,以便稍后在更改事件触发时获取它。
.addEventListener("change", inputChange)
使用- inputChange添加事件侦听器将在event
每次更改输入元素时接收一个对象。- inputChange 是事件处理函数。它提取输入元素的 id,并使用它来查找数据(
items
数组中的对象)Array.prototype.find()
(有关此原型的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/数组/查找)
// script.js
//Variables, Arrays, and Objects, dotNotation, bracketNotation
//Dom manipulation
let items = [
{
name: "Ironhack T",
price: 10,
image: "https://miro.medium.com/max/5190/1*aVsUjp1zvlRb1799gDjbLA@2x.jpeg",
},
{
name: "Ironhack Hoodie",
price: 15,
image:
"https://m.media-amazon.com/images/I/B1i3u9-Q-KS._AC_CLa%7C2140%2C2000%7CB1wqstnnTfS.png%7C0%2C0%2C2140%2C2000%2B0.0%2C0.0%2C2140.0%2C2000.0_UL1500_.png",
},
{
name: "Ironhack Sticker",
price: 2,
image:
"https://e7.pngegg.com/pngimages/887/803/png-clipart-ironhack-web-development-job-startup-company-design-blue-user-interface-design-thumbnail.png",
},
{
name: "Ironhack Mug",
price: 8,
image:
"https://d0bb7f9bf11b5ad1a6b2-6175f06f5e3f64e15abbf67415a276ec.ssl.cf1.rackcdn.com/product-images/designlab/11-oz-traditional-ceramic-coffee-mugs-7102-white1582888132.jpg",
},
];
/* Adds id property to objects inside items array */
items = items.map((item) => ({
...item,
id: item.name.replace(" ", "-").toLowerCase(),
}));
/* inputChange receives event object when the input changes */
function inputChange(event) {
// for inspection - log the event object
// console.log(event);
const { id } = event.target; // the id I gave to the input
const number = event.target.value; // the current value of the input
// find the object with the corresponding data in the items array
const data = items.find((item) => item.id === id);
console.log(
`I want to by ${number} of the item named, ${data.name} that costs $${data.price}`
);
}
let list = document.querySelector("ul");
items.forEach((item, i) => {
/* prettier-ignore */
list.innerHTML += `<li>
<div>Name: ${item.name}</div>
<div>Price: $${item.price}</div>
<img src="${item.image}" />
<input type='number' placeholder='quantity' id=${item.id} />
<button>Buy item</button>
</li>`;
});
/* Get all inputs */
const inputs = document.querySelectorAll("input");
inputs.forEach((inputEl) => inputEl.addEventListener("change", inputChange));
此外,关于脚本标记的 src 属性中的文件路径的一个词:在这种情况下,任何一种解决方案都可以:
<script src="script.js"></script>
<script src="./script.js"></script>
推荐阅读
- python - 如何在python中展平RDD?
- angular - Ionic [clear] property not working for a button
- vue.js - Vue / Apollo:如何更新新的订阅消息?
- collision-detection - 如何在 OimoJS 和 BABYLONJS 中使用碰撞
- javascript - POST 500(内部服务器错误)asp.net mvc
- select - 具有相同 v-model 的多个选择标签 (v-for)
- ruby - Ruby 文件无法打开
- python - 强制 ctypes.cdll.LoadLibrary() 从文件重新加载库
- vba - VBA中for循环内的if语句不起作用
- excel - 根据条件创建子列表