无法将 onclick 属性添加到可行的输入

Cannot add onclick property to input viable

本文关键字:输入 添加 onclick 属性      更新时间:2023-09-26

容易点。神秘问题。下面是我的代码。我为我的输入按钮创建了一个变量。我添加了一个点击功能。我将输入变量添加到现有的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')"';

尝试添加newbutton.onclick = sayhi;它将起作用。 OnClick 需要一个 JavaScript,该脚本将在单击该元素时执行。在这里addonclick只是一个变量,单击该元素时没有任何要执行的内容。

将 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");
}

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

newbutton.onclick = function(){sayhi('phrase')};
嘿,

你试过这种方式吗:

function sayhi(){
        alert("hi");
    }
var newbutton = document.createElement('input');
    newbutton.onclick = sayhi;
    newbutton.type = 'button'; 
    document.getElementById('existingdiv').appendChild(newbutton);