我想编写一个脚本,当用户点击它们时禁用所有提交按钮,我写了下面的Jquery脚本,可以在所有视图上使用,但它不起作用: -
$(document).ready(function () {
$(":input[type=submit]").click({
this.attr('disabled', 'disabled');
});
})
那么我的代码出了什么问题? BR
答案 0 :(得分:2)
$(document).ready(function () {
$("input[type='submit']").click(function() {
$(this).prop('disabled', true);
});
});
或
$(document).ready(function () {
$("input[type='submit']").click(function() {
this.disabled = true;
});
});
如果提交按钮正在提交表单,则必须阻止将重新加载页面的默认操作:
$("input[type='submit']").click(function(e) {
e.preventDefault();
$(this).prop('disabled', true);
});
});
答案 1 :(得分:0)
我认为这就是你要找的东西:
$("input[type=submit]").click(function() {
$(this).attr('disabled', 'disabled');
// if you want to disable all buttons on the form do the following
// $("input[type=submit]").attr("disabled", "disabled");
});
修改强>
adeneo是对的。使用prop()
方法可能是个好主意。我个人从未遇到通过attr('disabled', 'disabled')
禁用的问题,但我听过人们之前提到它。
但是,please-explain-attr-vs-prop-change-in-1-6上的这个jquery论坛帖子可能更能解释人们在使用attr()方法时遇到禁用问题的原因。他们很可能将其设置为true而不是禁用。
答案 2 :(得分:0)
这样的事情怎么样:
$(document).ready(function () {
$("form").submit({
$("input[type=submit]").attr('disabled', 'disabled');
return true;
});
});
上述将是实现您打算做的更好的方法。如果您坚持让代码工作,请在jQuery选择器中删除:
之前的input
。
答案 3 :(得分:0)
您说要禁用所有按钮,但“this”关键字仅引用导致事件被抛出的项目,因此您需要:
$(document).ready(function () {
$("input[type='submit']").click({
$("input[type='submit']").attr("disabled","disabled");
});
});
答案 4 :(得分:0)
您的脚本不起作用的原因是因为this
指的是HTML元素,而不是jQuery对象。您需要将其包装在jQuery对象中以在其上运行attr
等函数:
$(this).attr('disabled', 'disabled');
此外,如果您要禁用所有提交按钮,则需要执行新选择并将其全部禁用。这段代码应该做你想要的:
// Passing a function to $ will run it on document ready
$(function () {
$("input[type=submit]").click({
// Select all submit inputs and disable them
$('input[type=submit]').attr('disabled', 'disabled');
});
});
单击一个按钮后,现在应禁用所有提交按钮。
答案 5 :(得分:0)
在输入选择器中尝试不使用“:”并使用$(this)。
$(function () {
$("input[type=submit]").click(function() {
$(this).attr('disabled', 'disabled');
});
})
仅供参考 - 我在$(document).ready。
中使用了简写语法