我有两个HTML表单。第一个是searchFormSPECIAL.,第一个是searchForm。
不同之处在于,searchFormSPECIAL最初是在HTML中打印的,而当用户单击oooo按钮时,jQuery会附加jQuery。
我还设置了两个提交监听器$(“#searchForm”).submit(函数(事件)和.submit第一个是有效的,第二个是无效的。
这是我的代码:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$("#test_only").click(function () {
$('body').append(commentFormSPECIAL());
});
function commentFormSPECIAL() {
var comment_form_html = '<form action="/comment" id="searchFormSPECIAL">\
<input type="text" name="r" placeholder="Topic ID" />\
<input type="text" name="c" placeholder="Comment ..." />\
<input type="submit" value="Submit Comment" />\
</form>'
return comment_form_html;
//return "";
}
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
alert("Hey you are submitting searchForm")
});
$('#searchFormSPECIAL').submit(function(event){
/* stop form from submitting normally */
event.preventDefault();
alert("Hey you are submitting searchFormSPECIAL");
});
</script>
</head>
<body>
<div id="wrapper">
<form action="/new" id="searchForm">
<input type="text" name="s" placeholder="Topic..." />
<input type="text" name="l" placeholder="http://www.google.com" />
<input type="submit" value="Submit Topic" />
</form>
<button id="test_only">ooooo</button>
</div>
</body>
</html>
jQuery似乎没有识别附加形式。
提前感谢!
发布于 2013-02-11 05:56:52
当浏览器完全构造DOM层次结构时,应该绑定click事件。尝试将代码放入$(文档).ready中
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function () {
$("#test_only").click(function () {
$('body').append(commentFormSPECIAL());
});
function commentFormSPECIAL() {
var comment_form_html = '<form action="/comment" id="searchFormSPECIAL">\
<input type="text" name="r" placeholder="Topic ID" />\
<input type="text" name="c" placeholder="Comment ..." />\
<input type="submit" value="Submit Comment" />\
</form>'
return comment_form_html;
//return "";
}
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
alert("Hey you are submitting searchForm")
});
$(document).on('submit', '#searchFormSPECIAL', function (event) {
/* stop form from submitting normally */
event.preventDefault();
alert("Hey you are submitting searchFormSPECIAL");
});
});
</script>
</head>
<body>
<div id="wrapper">
<form action="/new" id="searchForm">
<input type="text" name="s" placeholder="Topic..." />
<input type="text" name="l" placeholder="http://www.google.com" />
<input type="submit" value="Submit Topic" />
</form>
<button id="test_only">ooooo</button>
</div>
</body>
</html>
发布于 2013-02-11 05:45:23
看起来,在表单实际创建之前,您正在尝试绑定到searchFormSPECIAL提交操作。
试着改变
$('#searchFormSPECIAL').submit(function(event){
至
$('#searchFormSPECIAL').on("submit", function(event){
https://stackoverflow.com/questions/14806532
复制相似问题