📜  如何在 jQuery 中使用 input readonly 属性?

📅  最后修改于: 2022-05-13 01:55:52.645000             🧑  作者: Mango

如何在 jQuery 中使用 input readonly 属性?

使用 jQuery 方法将readonly 属性添加到表单输入字段。

  • jQuery attr() 方法:此方法设置/返回所选元素的属性和值。如果使用该方法返回属性值,则返回第一个选中元素的值。如果使用此方法设置属性值,则为选中元素集合设置一个或多个属性/值对。

    句法:

    • 返回一个属性的值:
      $(selector).attr(attribute)
      
    • 设置属性和值:

      $(selector).attr(attribute, value)
      
    • 使用函数设置属性和值:
      $(selector).attr(attribute, function(index, currentvalue))
      
    • 设置多个属性和值:
      $(selector).attr({attribute:value, attribute:value, ...})
      

    参数:

    • 属性:此参数指定属性的名称。
    • value:该参数指定属性的值。
    • 函数(index, currentvalue):该参数指定返回要设置的属性值的函数。
      • index:该参数接收元素在集合中的索引位置。
      • currentValue:该参数接收所选元素的当前属性值。
  • jQuery prop() 方法:此方法设置/返回匹配元素的属性和值。如果此方法用于设置或返回属性值,则返回第一个选定元素的值。如果此方法用于设置属性值,则它为一组选定元素设置一个或多个属性/值对。

    句法:

    • 返回一个属性的值:
      $(selector).prop(property)
      
    • 设置属性和值:

      $(selector).prop(property, value)
      
    • 使用函数设置属性和值:
      $(selector).prop(property, function(index, currentvalue))
      
    • 设置多个属性和值:
      $(selector).prop({property:value, property:value, ...})
      

    参数:

    • property:此参数指定属性的名称。
    • value:此参数指定属性的值。
    • 函数(index, currentvalue):此参数指定一个函数,该函数返回要设置的属性值。
      • index:该参数接收元素在集合中的索引位置。
      • currentValue:此参数接收所选元素的当前属性值。

示例 1:在此示例中,通过使用attr() 方法启用表单输入文本字段的只读属性

 
 
     
         
            Add a readonly attribute to an input field
        
          
        
     
      
     
      
        

              GeeksForGeeks          

                   

            The readonly attribute is added to input box             on click on the button.         

                   
            Input :         
        
                                       

        

                                               

输出:

  • 点击按钮前:
  • 点击按钮后:

示例 2:在此示例中,通过使用prop() 方法启用表单输入文本字段的只读属性

 
 
     
         
            Add a readonly attribute to an input tag
        
          
        
     
      
    
           
        

              GeeksForGeeks          

                   

            The readonly attribute is added to input box             on click on the button.         

                   
            Input :         
        
                                       

        

                                               

输出:

  • 点击按钮前:
  • 点击按钮后:

jQuery 是一个开源 JavaScript 库,它简化了 HTML/CSS 文档之间的交互,它以其“少写,多做”的理念而广为人知。
您可以按照此 jQuery 教程和 jQuery 示例从头开始学习 jQuery。