![](/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.