我想通过使用javascript动态创建标签

时间:2019-12-30 05:22:51

标签: javascript

我正在使用引导程序模式。 当我单击模式按钮时,要在body标签上动态创建按钮的功能。 Description about function what I apply: As soon as I click the bluebutton, I want to create it at the body tag('beside the '+' button')

       window.onlaod = function(){
                var blue = document.getElementById('blue');

                blue.onclick = function(){
                    blue.onclick = null;

                    var result = document.getElementById('result');
                    var newblue = document.createElement('span');
                    newblue.id = 'newblue';
                    newblue.innerHTML += '<button type="button" class="btn btn-primary btnWH " id="blue"></button>';

                    result.appendChild(newblue);
                };
            };

    -> This is the code about event after click the bluebutton.


        <!-- label color -->
        <div class="modal-body">
            <button type="button" class="btn btn-primary btnWH " id="blue"></button>


          </div>

    -> This is the code about bluebutton.



        <div class="card border-secondary mb-3" style="max-width: 20rem;">
            <div class="card-header">Header</div>
                <div class="card-body">



                <div id="result">
                    <span id="first">
                        <button type="button" class="btn btn-primary plusbtn" data-toggle="modal" data-target="#mymodal"> +
                        </button>
                </span>
                </div>
            </div>
        </div>

-> This is the code about '+'button.

1 个答案:

答案 0 :(得分:0)

在结果代码的div ID内单击添加按钮时,将创建一个按钮,如下所示:

<html>
<body>
    <button type="button" id="blue">add</button>
    <div id="result"></div> 
    <script>
        window.onload = function() {
            return addEvent();
        }

        function addEvent() {
            var blueButton = document.getElementById('blue');

            blueButton.addEventListener("click", addButton)
        }

        function addButton() {
            var result = document.getElementById('result');
            var newBtn = document.createElement('span');

            newBtn.id = 'newblue';
            newBtn.innerHTML += '<button type="button" id="blue">test</button>';

            result.appendChild(newBtn);
        }
        </script>
    </body>
</html>