我有一个模式从jvascript拉出rails的动作 在它我有一个表格。我想捕获输入密钥并阻止默认提交, 问题是模态中的代码在模态中不会启动但在不在模态中时工作正常。
这是我的代码
表格
<form class="new_comment" id="new_comment" action="/selfies/1/comments" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓">
<input type="hidden" name="authenticity_token" value="XtAnNJPr+yjar3BQtyVK36a28bsvUyYInDbEBg1OOQmy4ammdt9pcR/mgCD6n7XhwGoHOMIIQCNffnN5SBTeHw==">
<textarea row="1" class="form-control" name="comment[body]" id="comment_body"></textarea>
</form>
这是我的javascript代码
$("#new_comment").on("keypress", function(e) {
if (e && e.keyCode === 13) {
e.preventDefault();
return $(this).submit();
}
});
这是模态
中的表格<div class="lightbox" style="display: block;">
<div class="lightbox_container">
<div class="lightbox_container_image">
<img src="/uploads/selfy/photo/1/20161213_123423.jpg" alt="">
</div>
<div class="lightbox_container_meta">
<div class="content" data-behavior="comments" data-selfie-id="1">
<p>first comment</p>
<p>secondly</p>
<p>heya</p>
</div>
<form class="new_comment" id="new_comment" action="/selfies/1/comments" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="XtAnNJPr+yjar3BQtyVK36a28bsvUyYInDbEBg1OOQmy4ammdt9pcR/mgCD6n7XhwGoHOMIIQCNffnN5SBTeHw==">
<textarea row="1" class="form-control" name="comment[body]" id="comment_body"></textarea>
</form>
</div>
</div>
</div>
答案 0 :(得分:0)
你可以试试这个:
$(document).ready(function(){
$("#new_comment").on("keypress", function(e) {
if (e && e.keyCode === 13) {
debugger;
e.preventDefault();
return $(this).submit();
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="lightbox" style="display: block;">
<div class="lightbox_container">
<div class="lightbox_container_image">
<img src="/uploads/selfy/photo/1/20161213_123423.jpg" alt="">
</div>
<div class="lightbox_container_meta">
<div class="content" data-behavior="comments" data-selfie-id="1">
<p>first comment</p>
<p>secondly</p>
<p>heya</p>
</div>
<form class="new_comment" id="new_comment" action="/selfies/1/comments" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="XtAnNJPr+yjar3BQtyVK36a28bsvUyYInDbEBg1OOQmy4ammdt9pcR/mgCD6n7XhwGoHOMIIQCNffnN5SBTeHw==">
<textarea row="1" class="form-control" name="comment[body]" id="comment_body"></textarea>
</form>
</div>
</div>
</div>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>
答案 1 :(得分:0)
写这样的事件
$(document).on("keypress","#new_comment", function(e) {
...
}