javascript - 无法使用 jQuery 从 html 选择中删除只读

标签 javascript jquery html

我正在尝试从某些 HTML 元素中动态删除“只读”属性。

我创建了一个 [JSFiddle here][1] 来显示我的问题,这是我的代码片段:

$('#theButton').on('click', function() {
  $('#mySelect').removeProp('readonly');
  $('#textInput').removeProp('readonly');
  //stop the form posting back
  return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>Some input fields</label>
  <input type='text' class='form-control' id='textInput' readonly>
  <select id='mySelect' readonly class='form-control input-sm '>
    <option>1</option>
    <option>2</option>
    </select>
  <button class='btn btn-primary' id='theButton'>
    Enable Button
    </button>
</form>

最佳答案

您对 removeProp 的使用不正确。

The .removeProp() method removes properties set by the .prop() method.

看看 JQuery 文档是怎么说的:

Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

你必须使用 prop这样做的属性(property)

Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

Fiddle

片段

$('#theButton').on('click', function() {
  $('#mySelect').prop('disabled', false);
  $('#textInput').prop('readonly', false);
  return false;
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
   <label>Some input fields</label>
   <input type='text' class='form-control' id='textInput' readonly>
   <select id='mySelect' disabled class='form-control input-sm '>
       <option>1</option>
       <option>2</option>
   </select>
   <button class='btn btn-primary' id='theButton'>Enable Button </button>
</form>

关于javascript - 无法使用 jQuery 从 html 选择中删除只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44364626/

相关文章:

javascript - 如何在没有持续回流的情况下动态调整高度的文本区域?

javascript - Superfish Child Drop Downs 掉落页面

javascript - 在哪里可以找到 Traceur(ES6 转换器)运行时?

javascript - 动态调用 javascript src url

asp.net - 在文本框正下方显示日历

javascript - 文本没有出现在 DOM 对象中?

javascript - 是否有更好/更短的模式来在另一个对象上设置对象属性的子集?

javascript - 使用简单的 JavaScript 重新定位按钮

javascript - 在焦点和 Tab 键按下时切换元素的类

html - 对齐表格中多行的多个单元格项