![](/img/trans.png)
[英]html input element still using “disabled” style, after remove “disabled” attribute via javascript
[英]Add disabled attribute to input element using Javascript
我有一个输入框,我希望它被禁用,同时隐藏它以避免移植我的表单时出现问题。
到目前为止,我有以下代码来隐藏我的输入:
$(".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);
以上所有都是完全有效的解决方案。 选择最适合您需求的一种。
您可以获取 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';
});
});
由于问题是询问如何使用 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"; }
只需使用 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.