1. 程式人生 > >js動態新增input按鈕並給按鈕增加onclick的函式事件(帶引數)

js動態新增input按鈕並給按鈕增加onclick的函式事件(帶引數)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script type="text/javascript">
        //onclick事件傳入value值和id
            function bt1(value, id) {
            //判斷點選的按鈕的id是否存在,不存在則建立,存在則alert
                if(!document.getElementById(id)) {
                //建立input元素
var inp = document.createElement("input"); inp.type = "button"; //傳入點選按鈕的value值到新的按鈕 inp.value = value; //傳入點選按鈕的id到新的按鈕(傳入是id+1防止重複) inp.id = id; //當方法有引數時,用onclick = 方法名(引數)時就有錯了,需要在方法名前面加function()
inp.onclick = function() { b1(id); }; document.getElementById("div").appendChild(inp); } else { alert("已存在") } } function b1(id) { var
flag = confirm("確認刪除?"); if(flag) { document.getElementById(id).remove(); } }
</script> <style type="text/css"> #div { width: 600px; height: 450px; border: 1px solid black; } #div2 { width: 600px; height: 50px; border: 1px solid black; } input { margin-left: 21px; width: 90px; height: 45px; } </style> </head> <body> <div id="div"></div> <div id="div2"> <input type="button" id="bt1" value="體育" onclick="bt1(this.value,this.id+1)" /> <input type="button" id="bt2" value="語文" onclick="bt1(this.value,this.id+1)" /> <input type="button" id="bt3" value="數學" onclick="bt1(this.value,this.id+1)" /> <input type="button" id="bt4" value="英語" onclick="bt1(this.value,this.id+1)" /> <input type="button" id="bt5" value="美術" onclick="bt1(this.value,this.id+1)" /> </div> </body> </html>