首页 > 解决方案 > 如何用 JS 创建一个 Button 并使用 OnClick 属性

问题描述

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

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

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

来自浏览器的代码

标签: javascriptjqueryhtmlfunctioncreateelement

解决方案


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

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


推荐阅读