jQuery .submit()不触发 [英] jQuery .submit() not triggering
问题描述
我做了很多搜索,但找不到为什么我的jQuery .submit()
不会触发。我也试着用 .click()
作为提交按钮。
我目前有一个div模板(包括表单):
< div class =回复现有消息style =display:无>
< form class =reply-message-form>
< input class =reply-to-message-idtype =hiddenname =PostReplyMessage [id]/>
< input class =post-reply-message-submittype =submitvalue =Reply/>
< / form>
< / div>
使用jQuery在单击回复按钮时将其添加到消息中(生成一个下拉回复表单所以用户可以回复消息)。这工作正常(双重使用萤火虫检查)。
然而,当我点击提交按钮时,我的jQuery代码不会产生警报,所以它甚至不会触发。有人能解释为什么会发生,谢谢! jQuery代码:
$(document).ready(function(){
$('。reply-message- (');
alert('test');
return false;
});
});
如果您要动态添加内容,到 .submit()
不会为你工作。这只会将事件处理程序绑定到与运行时匹配选择器的元素,所以添加的所有元素都不会绑定事件处理程序。
解决方案是事件代理,使用 .on ()
函数:
$(document).on('submit', '.reply-message-form',函数(e){
alert('test');
return false;
});
理想情况下,不是使用 document
,您'd选择包含所有动态内容的最接近的静态元素(即在页面加载时存在)。
另外,如果您使用的是jQuery版本在1.7之前,因此无法访问 .on()
函数,您可以使用
<$ c $> c)$(document).delegate('。reply-message-form','submit',function(e){
alert('test');
return false;
} );
I've done a lot of searching but can't find out why my jQuery .submit()
will not trigger. I've also tried with .click()
for the submit button.
I've currently got a div template (includes a form):
<div class="reply-to-existing-message" style="display: none">
<form class="reply-message-form">
<textarea id="post-reply-message-textarea" name="PostReplyMessage[message]" rows="3" cols="40" style="resize: none"></textarea>
<input class="reply-to-message-id" type="hidden" name="PostReplyMessage[id]" />
<input class="post-reply-message-submit" type="submit" value="Reply"/>
</form>
</div>
I append this to a message using jQuery when the reply button is clicked (produces a drop down reply form so user can reply to a message). This works fine (double checked using firebug too).
However, my jQuery code doesn't produce the alert when I click on the submit button, so it's not even triggering. Could someone please explain why this is occurring, thanks! jQuery code:
$(document).ready(function() {
$('.reply-message-form').submit(function() {
alert('test');
return false;
}) ;
});
If you're dynamically adding content, that static call to .submit()
isn't going to work for you. That will only bind the event handler to the elements that matched the selector at the time it was run, so any elements added after that won't have the event handler bound.
The solution is event delegation, using the .on()
function:
$(document).on('submit', '.reply-message-form', function(e) {
alert('test');
return false;
});
Ideally, rather than using document
, you'd select the closest static (i.e. exists when the page loads) element that will contain all of your dynamic content.
Alternatively, if you're using a version of jQuery prior to 1.7 and therefore don't have access to the .on()
function, you can use the .delegate()
function instead:
$(document).delegate('.reply-message-form', 'submit', function(e) {
alert('test');
return false;
});
这篇关于jQuery .submit()不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!