你能看到这段代码有什么问题吗?当用户点击第二个按钮
时,我有一个带有2个输入文本框和2个提交按钮的表单它应该列出以字母“J”开头的所有月份,但由于某种原因它不会运行
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>submit demo</title>
<style>
p {
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
span {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Type 'correct' to validate.</p>
<form action="javascript:alert( 'success!' );">
<div>
<input type="text" >
<input type="text" id ='months' >
<input type="submit" >
<input type="submit" id ="other" >
</div>
</form>
<span></span>
<script>
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
event.preventDefault();
});
$(document). ready(function() {
$( "#other" ).click(function() {
var months = [ 'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October',
'November', 'December'];
months = $.grep(months, function(value, i) {
return ( value.indexOf('J') == 0 );
});
$(' #months').html( '<li>' + months.join('</li><li>') + '</li>' );
});
})
</script>
</body>
</html>
答案 0 :(得分:0)
我修复了你的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>submit demo</title>
<style>
p {
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
span {
color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Type 'correct' to validate.</p>
<form action="javascript:alert( 'success!' );">
<div>
<input type="text" >
<input type="text" id ='months' >
<input type="submit" >
<input type="submit" id ="other" >
</div>
</form>
<span></span>
<ul id="m"></ul>
<script>
$(document). ready(function() {
$( "form" ).submit(function( event ) {
event.preventDefault();
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
});
$( "#other" ).click(function() {
var months = [ 'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October',
'November', 'December'];
$(months).each(function() {
if(this.indexOf('J') === 0)
$("#m").html($("#m").html()+"<li>"+this+"</li>");
});
});
});
</script>
</body>
您应该在click事件的第一行使用 event.preventDefault(),并使用jQuery函数 each()进行表迭代。