javascript - 如何用 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");
}
这是在浏览器中创建的代码
解决方案
在您的 myfunction() 上添加preventDefault()
警报之前的行,以防止重新加载页面(提交的默认行为 - 因为您的按钮位于表单上),然后您的警报将起作用。
否则,您可以在按钮上添加按钮类型,<button type="button">
以确保表单不会使其成为提交按钮
推荐阅读
- kubernetes - 如何将 kubernetes 中的服务暴露给 GCP/GKE 中的单个内部负载均衡器
- python-3.x - Python 3.6 numpy reshape 有效,但值包含 e
- python - 如何将 csv 转换为标记点的 RDD?
- cesium - 在 Cesium 中,tileset 上的 Clipping Planes 不起作用
- android - 在 Oreo 8.1 上更改通知通道的声音和振动
- intellij-idea - 如何在 IntelliJ 插件中实现“语音气泡”?
- scala - 使用 map 创建数组的副本(具有泛型类型)会导致错误 [Scala]
- reactjs - 流:缺少 T 的类型注释
- java - 需要使用反射和注释从父类构造函数实例化子类成员
- java - com.querydsl.core.Tuple 的 ClassCastException