我想给所有.firstname-显示输入中的内容,但我不知道该怎么做。这是代码:

    <input type="text" id="firstname" name="firstname" placeholder="First name">
    <button id="firstname-btn" onclick="show()">SHOW</button>
    <div class="firstname-show"></div>
    <div class="firstname-show"></div>


    function show() {
       var name = document.getElementById('firstname').value;
       document.querySelectorAll('.firstname-show').textContent = name;
    }

最佳答案

查询选择器将返回一个数组,因此您必须使用for循环进行迭代。见下面的功能。

function show() {
    var name = document.getElementById('firstname').value;
    var elements = document.querySelectorAll('.firstname-show');

    for(var i in elements){
        elements[i].textContent = name;
    }
}


https://jsfiddle.net/kagf25c1/

关于javascript - 显示多个div的输入内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60236966/

10-13 04:21