Javascript 如何添加和删除属性“只读”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2496443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:38:55  来源:igfitidea点击:

How I can add and remove the attribute "readonly"?

javascriptjquery

提问by question_about_the_problem

$(document).ready(function() {
  //Check City Value
  var city_value = parseInt($("#city").val());
  if( city_value == 0) {
     $("#state").attr("readonly", true);
     //$("#rate").attr("readonly", "readonly");   
  } else {
     $("#state").removeAttr("readonly");
     //document.getElementById("state").removeAttribute("readonly",0);
     //get_states(city_value);
  }
 /***
  //Check State Value
  var state_value = parseInt($('#state').val());
  if( state_value == 0) {
      $('#rate').attr('readonly', true); 
  } else {
     $('#rate').attr('readonly', false);
  }
  ***/
});

Here is my sample codes.

这是我的示例代码。

<td><select name="city" id="city">
<option value="0">PLEASE_SELECT_TEXT</option>
<option value="Antalya">Antalya</option>
<option value="Bodrum">Bodrum</option>
<option value="Istanbul">Istanbul</option>
</select>&nbsp;</td>
<td><div id="states"><input type="text" name="state" value="FORCE_FOR_SELECT" readOnly id="state"></div></td>

I've also added doctype:

我还添加了文档类型:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

回答by question_about_the_problem

Yes, finally I've found the solution. I've used onChange function.

是的,我终于找到了解决方案。我使用过 onChange 函数。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
//$(document).ready(function() {
function check_city(city_value) {
  //Check City Value
  city_value = $("#city").val();
  if( city_value == "0") {
     $("#state").attr("readonly", true);
     //$("#rate").attr("readonly", "readonly");   
  } else {
     $("#state").attr("readonly", false);
     //$("#state").removeAttr("readonly");
     //document.getElementById("state").removeAttribute("readonly",0);
     //get_states(city_value);
  }
 /***
  //Check State Value
  var state_value = parseInt($('#state').val());
  if( state_value == 0) {
      $('#rate').attr('readonly', true); 
  } else {
     $('#rate').attr('readonly', false);
  }
  ***/
//});
}
</script>

<td><select name="city" id="city" onChange="check_city(this.value)">
<option selected value="0">PLEASE_SELECT_TEXT</option>
<option value="Antalya">Antalya</option>
<option value="Bodrum">Bodrum</option>
<option value="Istanbul">Istanbul</option>
</select>&nbsp;</td>
<td><div id="states"><input type="text" name="state" value="FORCE_FOR_SELECT" readonly id="state"></div></td>

回答by BalusC

Works fine here in all major browsers I have. Here's an SSCCE:

在我拥有的所有主要浏览器中都可以正常工作。这是一个SSCCE

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2496443</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('#toggle').click(function() {
                    $('#foo').attr('readonly', !$('#foo').attr('readonly'));
                });
            });
        </script>
        <style>
            input[readonly] { 
                background: lightgray;
            }
        </style>
    </head>
    <body>
        <input id="foo">
        <button id="toggle">toggle readonly</button>
    </body>
</html>

Toggling it turns the background gray (although not all browsers do that) and the input is uneditable (this is consistent among all webbrowsers). So your problem lies somewhere else. You're probably using a poor doctypeand possibly also in combination with a poor webbrowser.

切换它会使背景变成灰色(尽管并非所有浏览器都这样做)并且输入是不可编辑的(这在所有网络浏览器中都是一致的)。所以你的问题出在其他地方。您可能使用了糟糕的文档类型,也可能与糟糕的网络浏览器结合使用。

回答by Guffa

While the readonlyproperty takes a boolean value, the readonlyattribute takes a string value. You should use the code that you have commented out:

虽然readonly属性采用布尔值,该readonly属性需要一个字符串值。您应该使用已注释掉的代码:

$("#rate").attr("readonly", "readonly");

回答by simhumileco

You can do it in pure JavaScript(or Vanilla JS) withoutjQuery:

你可以在没有jQuery 的纯 JavaScript(或Vanilla JS)中做到这一点

Set attributereadOnly:

设置属性readOnly

document.getElementById("state").readOnly = true;

and unset:

并取消设置

document.getElementById("state").readOnly = false;

Equivalentto object-oriented notationis also this array-oriented notation:

等价面向对象的表示法也是这种面向数组的表示法

document.getElementById("state")['readOnly']

It is also important that in JavaScriptall the properties are case sensitive, so it is important to remember about the large Oin the readOnlyproperty, otherwise it will not work...

同样重要的是,在JavaScript的所有属性是大小写敏感的,所以重要的是要记住大OreadOnly财产,否则将无法工作...