计数器按钮和新按钮

时间:2015-07-27 03:00:15

标签: javascript html

我正在尝试创建按钮,单击它时会返回单击按钮的次数以及每次单击按钮时;

页面上添加了一个新按钮(这是一个新按钮,因此尚未点击)添加到页面的每个按钮应与第一个按钮具有相同的交互。单击它会增加它的值并在页面上创建新按钮。

到目前为止,我已经找到了计数器按钮,但似乎无法在页面上添加按钮。请帮忙......

var clicks = 0;
function onClick(){
    clicks +=1;
    document.getElementById("button").innerHTML=  "I've been clicked " +clicks + 
" times" ;
};

2 个答案:

答案 0 :(得分:0)

createElement()方法可能是最简单的方法...... http://www.w3schools.com/jsref/met_document_createelement.asp

var clicks = 0;
var button = 0;
function onClick(){
    clicks +=1;
    button++
    document.getElementById("button").innerHTML=  "I've been clicked " +clicks + 
" times" ;
    var newButton = document.createElement("button"+button);
    document.body.appendChild(newButton);
    document.getElementById("button"+button).innerHTML = "I Have Not Been Clicked Yet"
};

答案 1 :(得分:0)

这是我的代码!希望它可以帮助你...

<!DOCTYPE html>
<html lang = 'es'>
    <head>
        <title> MY TEST </title>
        <meta charset = 'utf-8'>

    </head>
    <body id = 'body'>
        <input type = 'button' value = 'Clicked 0 times' id = 'Button' data-clicks = 0 ></input>

        <script>
            var firstButton = document.getElementById('Button');
            firstButton.addEventListener('click', createAndAdd);

            function createAndAdd(e){
                var button = e.target;

                // Reference to the data-clicks attribute
                var clicksAttribute = button.getAttribute('data-clicks');

                var clicksAttributeValue = parseInt(clicksAttribute);           
                button.value = 'Clicked ' + (clicksAttributeValue + 1) + ' times';

                clicksAttribute = clicksAttributeValue + 1;
                button.setAttribute('data-clicks', clicksAttribute);

                //Creating and adding the attributes of the new button.
                newInputButton = document.createElement('input');
                newInputButton.setAttribute('type', 'button');
                newInputButton.setAttribute('value', 'Clicked 0 times');
                newInputButton.setAttribute('id', 'Button');
                newInputButton.setAttribute('data-clicks', 0);

                //Adding the event Listener to the new button
                newInputButton.addEventListener('click', createAndAdd)

                //Adding the new button to the body
                var body = document.getElementById('body');
                body.appendChild(newInputButton);

            }
        </script>
    </body>
</html>