【问题标题】:How to create an Button with JS and use the OnClick Attribute [duplicate]如何使用 JS 创建按钮并使用 OnClick 属性 [重复]
【发布时间】:2020-04-27 10:31:49
【问题描述】:

我想使用我用 JS 创建的带有 OnClick 的按钮。 我可以创建按钮,也可以将属性添加到 Button,但 Button 不会启动我的功能,他只会重置网站。

          $.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data:{status:status},
success: function(data){
    var anzahl = data;
    status = 1;
    while (anzahl>nummer) {
      nummer++;
    $.ajax({
        type: "POST",
        url: "http://localhost/jQuery&PHPnew/Markt.N.php",
        data:{nummer:nummer, status:status},
        success: function(data){
          var Daten = JSON.parse(data);
          var Ausgabebereich = document.getElementById('main');
          var f = document.createElement("form");

          var bInhalt = document.createElement('button');
          var Inhalt = document.createTextNode("Senden");
          bInhalt.appendChild(Inhalt);
          bInhalt.setAttribute("onclick", "myfunction()");
          f.appendChild(bInhalt);

          Ausgabebereich.appendChild(f);
        }

    })
}
}
})
function myfunction() {
alert("pls");
}

这是在浏览器中创建的代码

Code from the Browser

【问题讨论】:

  • 如果按钮在表单内并且没有将 type 属性设置为“button”,它将作为“提交”按钮,因此提交和重定向/刷新页面。

标签: javascript jquery html function createelement


【解决方案1】:

在您的 myfunction() 上,在警报前添加行 preventDefault(),以防止重新加载页面(提交的默认行为 - 因为您的按钮位于表单上),然后您的警报将起作用。

否则,您可以在按钮上添加按钮类型,如 <button type="button"> 以确保表单不会使其成为提交按钮

【讨论】:

  • 好的,它现在没有加载新的一面,但功能没有启动你知道为什么
  • 您添加的是type="button" 还是preventDefault()
  • type= 按钮
  • 把你的函数放在jquery的“pageload”中,如下:$( document ).ready(function() { function myfunction() { alert("pls"); } });
  • 它现在也不起作用,错误是找不到变量myfunction
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多