如何使用按钮多次添加文本和输入

我正在创建一个网站,允许用户指定数量的输入。我希望用户能够单击一个按钮,然后会出现一个新的文本和输入框,他们可以输入。


这是我当前的代码:


<!-- adds new company input field everytime button is clicked -->

        <input type="button" onclick="addInput()">

        <span id="companyX"></span><span id="companyBoxX"></span>

        <script>

            var countBox = 2;

            var boxName = 0;


            function addInput()

            {

                var boxName = "Company " + countBox;


                var company = document.getElementById("companyX");

                company.innerHTML += boxName;

                var newBreak = document.createElement('br');

                company.appendChild(newBreak);


                document.getElementById('companyBoxX').innerHTML+='<br/><input type="text" id="'+boxName+'" value="'+boxName+'" " /><br/>';

                countBox += 1;

            }

        </script>

目前的问题是,每次我尝试添加新文本或输入字段时,它只会附加到当前文本或输入。我希望它们并排出现在新行上。前任:


Company 1: (Input Box 1)

Company 2: (Input Box 2)

...

我对 Javascript 和 HTML 非常陌生,任何帮助将不胜感激。谢谢!


慕田峪4524236
浏览 106回答 2
2回答

忽然笑

我相信你走在正确的道路上。看看这是否更接近您的需要。&nbsp; &nbsp; var countBox = 2;var boxName = 0;function addInput(){&nbsp; &nbsp; var boxLabel = "<label>Company " + countBox + "</label>";&nbsp; &nbsp; var element = document.getElementById('my-content');&nbsp; &nbsp; var html = '<div class="row">'+boxLabel+': <input type="text" id="'+boxName+'" value="'+boxName+'" " /></div>';&nbsp; &nbsp; appendHtml(element, html);&nbsp; &nbsp; countBox += 1;&nbsp; &nbsp; boxName += 1;}function appendHtml(el, str) {&nbsp; &nbsp; var div = document.createElement('div');&nbsp; &nbsp; div.innerHTML = str;&nbsp; &nbsp; while (div.children.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; el.appendChild(div.children[0]);&nbsp; &nbsp; }}<input type="button" onclick="addInput()" value="Add new"><div id="my-content" class="content"></div>我相信这更接近您的需要?

呼啦一阵风

您使用了正确的东西并且有点封闭...阅读代码并在有不清楚的地方添加评论。希望能帮助到你let myButton = document.querySelector('#add-those-inputs');myButton.addEventListener('click', event => { addInput(); });let myPlaceholder = document.querySelector('.my-placeholder');let addInput = function() {&nbsp; &nbsp; let companyInputCounter = document.querySelectorAll('.my-company-input');&nbsp; &nbsp; let inputWrapper = document.createElement('div');&nbsp; &nbsp; let input = document.createElement('input');&nbsp; &nbsp; input.classList.add('my-company-input');&nbsp; &nbsp; input.type = 'text';&nbsp; &nbsp; input.value = 'Company_' + companyInputCounter.length;&nbsp; &nbsp; input.id = 'Company_' + companyInputCounter.length;&nbsp; &nbsp; inputWrapper.appendChild(input);&nbsp; &nbsp; myPlaceholder.appendChild(inputWrapper);};<input id="add-those-inputs" type="button" value="Click me to add more"><div class="my-placeholder"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5