jQuery设置内容和属性

jQuery设置内容和属性

设置内容:它是用来设置使用jQuery的内容。以下是用于设置内容的方法,如下所示。

  • text()。它用于设置或返回选定元素的文本内容。
  • html()。它用于设置或返回所选元素的innerHTML内容。
  • val()。这个参数用于设置或返回所选元素的属性值。这个方法适用于HTML表单元素。

例子:这个例子使用set content方法(text(), html()和val()方法)来设置内容。

<!DOCTYPE html>
<html>
  
<head> 
    <title>jQuery Set Content</title>
      
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
</head> 
  
<body style="text-align:center;">
      
    <h1 id="GFG1" style = "color:green;">
        GeeksForGeeks
    </h1>
      
    <h2 id="GFG2">jQuery Set Content</h2>
      
    <p>Full Form: <input type="text" id="GFG3" value="GFG"></p>
      
    <button id="btn1">Set 1 line</button>
    <button id="btn2">Set 2 line</button>
    <button id="btn3">Set 3 line</button>
      
    <!-- Script to set the content -->
    <script>
        (document).ready(function() {
            ("#btn1").click(function() {
                ("#GFG1").text("GEEKSFORGEEKS");
            });
              
            ("#btn2").click(function() {
                ("#GFG2").html("<b>Set Content</b>");
            });
              
            ("#btn3").click(function() {
                $("#GFG3").val("GeeksForGeeks");
            });
        });
    </script>
</body>
  
</html>  

输出:

  • 在点击按钮之前。
    jQuery设置内容和属性
  • 之后点击设置1行按钮。
    jQuery设置内容和属性
  • 之后点击设置2行按钮。
    jQuery设置内容和属性
  • 之后点击设置3行按钮。
    jQuery设置内容和属性

设置属性: jQuery中的jQuery attr()方法是用来设置和改变属性值的。

例子:这个例子使用attr()方法来设置和改变属性值。

<!DOCTYPE html>
<html>
  
<head> 
    <title>jQuery Set Attributes</title>
      
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
</head> 
  
<body style="text-align:center;">
    
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
    <h2>jQuery Set Attributes</h2>
      
    <button id="btn1">Click</button>
      
    <br><br>
      
    <h3>
        <a href="https://geeksforgeeks.org" id="GFG">
            geeksforgeeks.org
        </a>
    </h3>
      
    <!-- Script to use set attribute method -->
    <script>
        (document).ready(function() {
            ("button").click(function() {
                $("#GFG").attr("href", 
"https://www.geeksforgeeks.org/jquery-introduction/");
            });
        });
    </script>
</body>
  
</html>  

输出:

  • 在点击链接之前。
    jQuery设置内容和属性
  • 在点击按钮之前先点击链接。
    jQuery设置内容和属性
  • 点击按钮后点击链接。
    jQuery设置内容和属性

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程