【问题标题】:Add input tag inside HTML via JS and increasing input id inside JS通过 JS 在 HTML 中添加输入标签并在 JS 中增加输入 id
【发布时间】:2021-01-01 00:13:16
【问题描述】:

我想写一个网站,你可以在一个文本输入中写 3 封电子邮件。但是,我还添加了一个按钮,它为另一个电子邮件添加了另一个文本输入。我的问题是,我想使用以下代码添加新添加的 Element 一个 id:email.setAttribute('id','increasing_number');。但是,它无法按照我希望的方式工作。完整代码和结果:

function test() {
    let ul =document.getElementById('ul');
    var li = document.createElement('li');
    var y = 4;
    var email = document.createElement('input');
    email.setAttribute('id',y); //<--
    email.setAttribute('placeholder','E-Mail');
    email.setAttribute('type','email');
    email.setAttribute('name','email');
    email.setAttribute('required','');
    li.appendChild(email);
    ul.appendChild(li);
    y = y++;
}
<ul id="ul">
    <li>...</li>
    <li>...</li>
    <li>...</li>
    <li>
        <input id="4" placeholder="E-Mail" type="email" name="email" required="">
    </li>
    <li>
        <input id="4" placeholder="E-Mail" type="email" name="email" required="">
    </li>
</ul>

您可以看到它应该显示在第 5 封电子邮件 input id="5" 但它没有。它显示数字 4。它不会将 y 的旧值保存在 JS 文件中,也不会正确增加它。

【问题讨论】:

标签: javascript html input


【解决方案1】:

您的代码每次运行时都会将 y 初始化为 4。你可以有一个函数参数来保存元素的 id 变量,然后你可以在 for 循环中调用它。

function test(id){
    let ul = document.getElementById('ul');
    let li = document.createElement('li');
    let email = document.createElement('input');
    email.setAttribute('id', id);
    email.setAttribute('placeholder', 'E-mail');
    email.setAttribute('type', 'email');
    email.setAttribute('name', 'email');
    email.setAttribute('required','');
    li.appendChild(email);
    ul.appendChild(li);
}

for(let i=1; i<=5; i++){
    test(i);
}

【讨论】:

    猜你喜欢
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    相关资源
    最近更新 更多