gpt4 book ai didi

http - 使用 jQuery 附加 HTML 表单时提交按钮不起作用

转载 作者:可可西里 更新时间:2023-11-01 16:56:36 26 4
gpt4 key购买 nike

我有两个 HTML 表单。第一个是 searchForm,第二个是 searchFormSPECIAL

区别在于 searchForm 最初是在 HTML 中打印的,而 searchFormSPECIAL 是在用户单击按钮 oooo 时由 jQuery 附加的。 p>

我还设置了两个提交监听器$("#searchForm").submit(function(event)$("#searchFormSpecial").submit(function(event)。第一个有效,第二个无效。

这是我的代码:

<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 似乎无法识别附加表单。

提前致谢!

最佳答案

当浏览器完全构建了 DOM 层次结构时,您应该绑定(bind)点击事件。尝试将您的代码放入 $(document).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>

关于http - 使用 jQuery 附加 HTML 表单时提交按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14806532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com