我正在尝试使用用户HTML输入来更改javascript对象值



我正在尝试使用HTML"input"来更改apiData.id值。我是javascript的新手,不确定这是否正确。如有任何建议,我们将不胜感激。

const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
const newId = apiData.id;
function eventController(event) {
newId = event.target.value;
}
input.addEventListener('change', eventController, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>


<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>

newId是常量,因此在声明后不能为其赋值。

但是,即使您可以(并且您可以将其作为变量(,这也不会影响apiData.id,因为newId被分配了apiData.id,但它们并没有绑定在一起。

您应该直接为apiData.id分配一个新值:

const apiData = {
url: 'https://pokeapi.co/api/v2/',
type: 'pokemon',
id: '76',
}
const input = document.getElementById('container');
// const newId = apiData.id;
function eventController(event) {
apiData.id = event.target.value;
}
input.addEventListener('change', eventController, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pokemon</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<input id="input">
<input type="submit" value="Catch">
</div>


<div class="pokemon"></div>
<script src="main.js"></script>
</body>
</html>

最新更新