【问题标题】:Detect when input has a 'readonly' attribute检测输入何时具有“只读”属性
【发布时间】:2011-03-24 17:13:30
【问题描述】:

我想在输入具有“只读”属性时发出警报。我试过这个:

  if($('input').attr('readonly') == 'readonly'){

    alert("foo");
  }

我认为“如果”甚至不是最好的方法。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    最快的方法是使用.is() jQuery 函数。

    if ( $('input').is('[readonly]') ) { }
    

    使用[readonly] 作为选择器只是检查该属性是否在您的元素上定义。如果你想检查一个值,你可以使用这样的东西:

    if ( $('input').is('[readonly="somevalue"]') ) { }
    

    【讨论】:

    • 我试图仅在只读模式下阻止回发。我有一个 asp.net 页面。 stackoverflow.com/questions/30351993/…
    • 这有助于我根据其属性将基于 ajax 的表单重置为其默认值。 is 的反面 = not
    【解决方案2】:

    从 JQuery 1.6 开始,始终使用 .prop() 在此处阅读原因:http://api.jquery.com/prop/

    if($('input').prop('readonly')){ }
    

    .prop() 也可以用来设置属性

    $('input').prop('readonly',true);
    
    $('input').prop('readonly',false);
    

    【讨论】:

      【解决方案3】:

      没有 jQuery 的 javascript 怎么样?

      对于任何使用或不使用 jQuery 都可以获得的输入,只需:

      input.readOnly
      

      注意:记住camelCase

      【讨论】:

      • 想在ANGULAR(简单的事情)下做的事情,花了好几个小时才来到这里!感谢您的提醒,cameCase。
      【解决方案4】:

      检查“只读”属性的当前值,如果它是“假”(字符串)或空(未定义或“”),那么它不是只读的。

      $('input').each(function() {
          var readonly = $(this).attr("readonly");
          if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
              alert('this is a read only field');
          }
      });
      

      【讨论】:

        【解决方案5】:

        你可以只使用属性选择器,然后测试长度:

        $('input[readonly]').length == 0 // --> ok
        $('input[readonly]').length > 0  // --> not ok
        

        【讨论】:

          【解决方案6】:

          尝试一个简单的方法:

          if($('input[readonly="readonly"]')){
             alert("foo");
          }
          

          【讨论】:

            【解决方案7】:

            试试这个:

            if($('input').attr('readonly') == undefined){
                alert("foo");
            }
            

            如果它不存在,它将在 js 中为 undefined

            【讨论】:

              【解决方案8】:

              在 vanilla/pure javascript 中,您可以检查如下 -

              var field = document.querySelector("input[name='fieldName']");
              if(field.readOnly){
               alert("foo");
              }
              

              【讨论】:

                猜你喜欢
                • 2011-04-04
                • 1970-01-01
                • 2015-05-17
                • 2021-11-23
                • 2019-07-09
                • 2011-01-30
                • 2013-12-12
                • 2012-03-24
                • 1970-01-01
                相关资源
                最近更新 更多