javascript – 输入类型=“提交”按钮onClick:jQuery replaceWith阻止表单提交
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 输入类型=“提交”按钮onClick:jQuery replaceWith阻止表单提交,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2349字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 输入类型=“提交”按钮onClick:jQuery replaceWith阻止表单提交](/upload/InfoBanner/zyjiaocheng/731/ad6d2e8ec5584a169cccf97814aedad6.jpg)
我有以下HTML:
<input class="button" name="save" onclick="$(this).replaceWith('<img src=http://www.example.com/images/ajax-loader.gif />');" type="submit" value="SUBMIT">
单击该按钮时,表单不再尝试提交,而是用转动的AJAX加载gif替换自身,并且不执行任何操作.如果我删除onclick部分,它会提交.
长话故事,这是为了客户,但我不能以形式给他们相同的东西
$(function() { $(input[name=save]).on({click:function() { $(this).replaceWith(...); } }); });
更换后自己为什么还不提交?我不是e.preventDefault()在任何地方.
解决方法:
根据replaceWith()文档:
The .replaceWith() method removes content from the DOM and inserts new
content in its place with a single call.
根据remove()文档删除元素时:
In addition to the elements themselves, all bound events and jQuery
data associated with the elements are removed.
我假设这就是提交没有执行的原因.
如果您希望表单仍然提交,则可以在替换元素后手动触发提交.
DEMO – 在替换按钮元素时提交表单
为了便于阅读,为了演示,我已将click事件的绑定移动到脚本而不是元素的内联.我还在多个表单的情况下添加了一个id,如果你只有一个表单就不需要,因为你可以简单地绑定到$(“form”).on(“submit”)而不是
$("input[name='save']").on("click", function(){
$(this).replaceWith('<img class="submit-form" src=http://www.example.com/images/ajax-loader.gif />');
$("form").submit();
});
$("#myForm").on("submit", function(){
alert("form has been submitted.");
return false;
});
编辑 – 使用内嵌onclick的相同代码
将代码移动到内联onClick仍然有效.
关于表单提交,$(this)将是替换之前的按钮并且在之后消失,因此$(this).closest(“form”).submit()或使用$(this)赢得的任何其他形式的选择器不行.
您必须通过使用$(“form”).submit()或者如果您有多个表单使用$(“#myForm”)中的id而提交(),以便中立地提交表单而不使用$(this).submit().
<form id="myForm" action="http://jsfiddle.net/">
<input class="button" name="save" type="submit" onclick="$(this).replaceWith('<img src=http://www.example.com/images/ajax-loader.gif />'); console.log(this); $('#myForm').submit();" value="SUBMIT">
</form>
DEMO – 使用内联onclick替换按钮后手动提交表单
作为旁注,如果您希望在触发提交事件之前显示图像,您可以应用这样的小技巧:
$("input[name='save']").on("click", function(){
$(this).replaceWith('<img class="submit-form" src=http://www.example.com/images/ajax-loader.gif />');
// Makes sure the image is rendered before the submit executes.
window.setTimeout(function(){
$("form").submit();
}, 300);
});
您可以在内联的onClick中应用相同的课程.
内容总结
以上是互联网集市为您收集整理的javascript – 输入类型=“提交”按钮onClick:jQuery replaceWith阻止表单提交全部内容,希望文章能够帮你解决javascript – 输入类型=“提交”按钮onClick:jQuery replaceWith阻止表单提交所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。