如何使用JavaScript动态显示按钮?

如何使用JavaScript动态显示按钮?,javascript,button,dynamic,Javascript,Button,Dynamic,在下面的代码中,我试图在本地运行网页时使用Javascript动态创建一个按钮(我不想只创建一个带有HTML的按钮),但没有按钮出现 buttonActionFunction是我拥有的一个单独的功能(它完全工作),当点击按钮时会出现一个图像 还有,我该如何添加到代码中,以便一旦单击按钮,按钮就会停用,这样他们就不能再次单击它了 <script> function buttonFunction() { var button= document.createEle

在下面的代码中,我试图在本地运行网页时使用Javascript动态创建一个按钮(我不想只创建一个带有HTML的按钮),但没有按钮出现

buttonActionFunction是我拥有的一个单独的功能(它完全工作),当点击按钮时会出现一个图像

还有,我该如何添加到代码中,以便一旦单击按钮,按钮就会停用,这样他们就不能再次单击它了

<script>
    function buttonFunction() {
        var button= document.createElement("button");
        button.appendChild(document.createTextNode("Click Me"));
        button.onclick=buttonActionFunction();
        document.getElementById("divId").appendChild(button);
    }
    buttonFunction();
    </script>

函数按钮函数(){
var button=document.createElement(“按钮”);
appendChild(document.createTextNode(“单击我”);
button.onclick=buttonActionFunction();
document.getElementById(“divId”).appendChild(按钮);
}
按钮功能();
jsfiddle:

jsiddle:

添加到html中

至于禁用点击按钮

   function buttonActionFunction(e) {
        e.target.disabled = true
    }
button.onclick=buttonActionFunction
button.onclick=buttonActionFunction()

添加到html

至于禁用点击按钮

   function buttonActionFunction(e) {
        e.target.disabled = true
    }
button.onclick=buttonActionFunction
button.onclick=buttonActionFunction()

根据答案,我已更新代码,以在单击上一个按钮时禁用该按钮,如下所示:

function createButton(context){
    var button = document.createElement("input");
    button.type = "button";
    button.value = "Click Me";
    button.onclick = function() {functienaam(button)};
    context.appendChild(button);
}
 function functienaam(button)
 {
 createButton(document.body);
 button.disabled = true;
 }
createButton(document.body);

根据答案,我已更新代码,以在单击上一个按钮时禁用该按钮,如下所示:

function createButton(context){
    var button = document.createElement("input");
    button.type = "button";
    button.value = "Click Me";
    button.onclick = function() {functienaam(button)};
    context.appendChild(button);
}
 function functienaam(button)
 {
 createButton(document.body);
 button.disabled = true;
 }
createButton(document.body);

你能提供一个提琴或片段吗?@PunitGajjar我不明白你的意思,我是Javascript新手!提供工作示例并在此处分享感谢分享链接@lordkaincan你能分享你的html代码吗?你能提供一个提琴或代码片段吗?@PunitGajjar我不明白你的意思,我对Javascript不熟悉!提供工作示例并在此处共享感谢您共享链接@lordkaincan您可以共享html代码以添加到其中,
button.onclick=buttonActionFunction()
应该是
按钮。onclick=buttonActionFunction
然后确保在html文档中js代码()之前声明了
,以添加到其中,
button.onclick=buttonActionFunction()
应该是
按钮。onclick=buttonActionFunction
然后确保在js代码之前在html文档中声明了
),这太好了,谢谢,我让它工作了!我只是做了一些小小的改变。在你有functienaam的地方,我添加了我的函数,为按钮提供了动作,然后在botton,当你有createButton的时候,我刚刚删除了括号中的东西,现在它工作得很好。非常感谢你的帮助你绝对是传奇那太棒了,谢谢,我成功了!我只是做了一些小小的改变。在你有functienaam的地方,我添加了我的函数,为按钮提供了动作,然后在botton,当你有createButton的时候,我刚刚删除了括号中的东西,现在它工作得很好。非常感谢你的帮助,你绝对是个传奇