我有一个输入框,我希望禁用它并同时隐藏它,以避免移植表单时出现问题。
到目前为止,我有以下代码来隐藏我的输入:
$(".shownextrow").click(function() {
$(this).closest("tr").next().show().find('.longboxsmall').hide();
});
这是因此被隐藏的输入:
<input class="longboxsmall" type="text" />
我怎样才能将禁用属性添加到输入中?
$("input").attr("disabled", true);
截至...我不知道了。
已经是 2013 年 12 月了,我真的不知道该告诉你什么。
首先总是
.attr()
,然后总是.prop()
,所以我回来更新了答案并使其更加准确。
一年后 jQuery 再次改变了主意,我什至不想跟踪这一点。
长话短说,到目前为止,这是最好的答案:“你可以两者都使用......但这取决于情况。”
您应该阅读这个答案:https://stackoverflow.com/a/5876747/257493
他们针对该更改的发行说明包含在此处:
.attr() 和 .prop() 都不应该用于获取/设置值。请改用 .val() 方法(尽管使用 .attr("value", "somevalue") 将继续有效,就像 1.6 之前的那样)。
首选用途总结
.prop() 方法应该用于布尔属性/属性以及 html 中不存在的属性(例如 window.location)。所有其他属性(您可以在 html 中看到的属性)可以并且应该继续使用 .attr() 方法进行操作。
或者换句话说:
“.prop = 非文档内容”
“.attr”=文档内容
... ...
希望我们都能在这里学到有关 API 稳定性的教训...
来自我的来源的工作代码:
HTML 世界
<select name="select_from" disabled>...</select>
JS世界
var from = jQuery('select[name=select_from]');
//add disabled
from.attr('disabled', 'disabled');
//remove it
from.removeAttr("disabled");
如果您使用 jQuery,那么有几种不同的方法可以设置禁用属性。
var $element = $(...);
$element.prop('disabled', true);
$element.attr('disabled', true);
// The following do not require jQuery
$element.get(0).disabled = true;
$element.get(0).setAttribute('disabled', true);
$element[0].disabled = true;
$element[0].setAttribute('disabled', true);
$(element).prop('disabled', true); //true|disabled will work on all
$(element).attr('disabled', true);
element.disabled = true;
element.setAttribute('disabled', true);
以上都是完全有效的解决方案。选择最适合您需求的一款。
由于问题是询问如何使用 JS 执行此操作,所以我提供了一个普通的 JS 实现。
var element = document.querySelector(".your-element-class-goes-here");
// it's a good idea to check whether the element exists
if (element != null && element != undefined) {
element.disabled = "disabled";
}
可以获取DOM元素,直接设置disabled属性。
$(".shownextrow").click(function() {
$(this).closest("tr").next().show()
.find('.longboxsmall').hide()[0].disabled = 'disabled';
});
或者如果有多个,您可以使用
each()
来设置所有这些:
$(".shownextrow").click(function() {
$(this).closest("tr").next().show()
.find('.longboxsmall').each(function() {
this.style.display = 'none';
this.disabled = 'disabled';
});
});
只需使用 jQuery 的
attr()
方法
$(this).closest("tr").next().show().find('.longboxsmall').attr('disabled', 'disabled');
在JQuery中你可以使用以下函数:
$("input").prop('disabled', true);
$("input").prop('disabled', false);
对于原生js你可以使用:
document.getElementById("myElement").disabled = true;
$("input").attr('disabled', true);
我尝试了
.prop()
,但这对我来说在 JQuery 3.7.1 上不起作用