【问题标题】:I am trying to use an user HTML input to change a javascript object value我正在尝试使用用户 HTML 输入来更改 javascript 对象值
【发布时间】:2022-02-14 13:40:17
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

    标签: javascript html object


    【解决方案1】:

    newId 是 const,所以你不能在它被声明后给它赋值。

    但即使您可以(并且您可以,通过将其设为变量),这也不会影响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>

    【讨论】:

    • 感谢您的回复,我已经做出了您建议的更改,但仍然没有使用输入来更改 Pokemon ID。我添加了一个变量来显示 h1 标记中的输入,该标记有效,但是当我添加 apiData.id 时它什么也没做。
    • 那么代码中的其他地方还有另一个问题。在您在此处共享的代码部分中,没有其他问题。如果您使用我的修复程序运行它,请在输入字段中输入一些新 id 并按下按钮,apiData 将使用新 id 更新。您可以通过在apiData.id = event.target.value; 之后添加console.log(apiData); 来轻松验证。
    • 是的,你是对的!它确实 console.log 输入但现在我不确定它为什么不更新详细信息。谢谢奥里乌斯
    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多