0

轻松点。令人费解的问题。下面是我的代码。我为我的输入按钮创建了一个变量。我添加了一个 onclick 功能。我将输入变量添加到现有的 div 中。但是 onclick 属性没有出现。请帮忙。

    var newbutton = document.createElement('input');
    var addonclick = "'return sayhi('phrase')'";
    newbutton.onclick = addonclick;//does not work
    newbutton.type = 'button'; 
    document.getElementById('existingdiv').appendChild(newbutton);

...

    function sayhi(phrase){
        alert(phrase);
    }

也不起作用:

            newbutton.id = "buttonid";   
            ....              
            document.getElementById("buttonid").onload = '"return sayhi('phrase')"';
4

4 回答 4

1

尝试添加newbutton.onclick = sayhi;它会起作用。onclick 期望在单击该元素时执行的 javascript。这里addonclick只是一个变量,点击该元素时没有任何执行。

于 2013-09-25T05:07:46.683 回答
1

onclick 属性接受一个函数而不是字符串,例如

newbutton.onclick = function(){sayhi('phrase')};
于 2013-09-25T05:00:58.597 回答
1

将 sayhi 分配给 .onclick。也给你的按钮一些文字

var newbutton = document.createElement('input');
newbutton.onclick = sayhi;
newbutton.type = 'button';
newbutton.value = 'click'; 
document.getElementById('existingdiv').appendChild(newbutton);

function sayhi(){
    alert("hi");
}
于 2013-09-25T05:01:20.807 回答
0

嘿,你试过这样吗:

function sayhi(){
        alert("hi");
    }

var newbutton = document.createElement('input');

    newbutton.onclick = sayhi;
    newbutton.type = 'button'; 
    document.getElementById('existingdiv').appendChild(newbutton);
于 2013-09-25T05:04:12.673 回答