<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
function myf() {
alert("coming dude");
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
}
</script>
</head>
<body >
<form id="msj_form" >
<button id="add" value="add" onclick="myf()">ADD</button>
</form>
</body>
</html>
点击“添加”按钮时,selbox正在生成,但它的消失是立即...我的代码中有错误
点击“添加”按钮时,selbox正在生成,但它的消失是立即...我的代码中有错误
答案 0 :(得分:1)
因为在您的函数被调用后,表单已提交,所以您需要做的就是阻止表单提交。
试试这个:
<html>
<head>
</head>
<body>
<form id="msj_form" >
<button id="add" value="add">ADD</button>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function myf(e) {
e.preventDefault(); // <-- make sure to add this
alert("coming dude");
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
}
$('#add').on('click',myf);
</script>
</body>
</html>
如果您想了解有关preventDefault()
的更多信息,请参阅此处 - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
答案 1 :(得分:0)
问题是您的表单默认是提交的,所以要防止只使用preventDefault()方法。这是我的解决方案。希望它有所帮助!
function myf() {
alert("coming dude");
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
}
$(document).ready(function(){
$("#msj_form").submit(function(event){
event.preventDefault();
myf();
});
});
&#13;
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<form id="msj_form" >
<button id="add" value="add" >ADD</button>
</form>
&#13;