jQuery text()方法
这个方法是用来设置或返回元素的文本内容。在设置内容时,它覆盖了所有匹配元素的内容。text method()返回的内容被用来返回所有匹配元素的文本内容。
语法:
- 返回文本语法。
 
$(selector).text()
- 设置文本语法。
 
$(selector).text(content)
- 使用一个函数设置文本。
 
$(selector).text(function(index, currentcontent))
属性:
- 内容要求。它用于设置元素的新文本内容。
 - Function(index, currentcontent)。它用于指定一个函数,将返回所选元素的新文本内容。
- index : 它返回元素的索引位置。
 - currentcontent : 它返回元素的当前内容。
 
 
例子-1:设置文本语法。
<!DOCTYPE html>
<html>
  
<body>
    <h1>
      <center>
    Geeks <button onclick="function()">Click me
        </button>
      </center>
  </h1>
  
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
  </script>
    <script>
        (document).ready(function() {
            ("button").click(function() {
                $("p").text("Jquery_text_method");
            });
        });
    </script>
  
    <p>GeeksforGeeks</p>
    <p>Jquery</p>
  
</body>
  
</html>
输出:
在点击按钮之前:

点击按钮后:。

示例-2:返回文本语法。
<!DOCTYPE html>
<html>
  
<body>
    <h1>
      <center>
     Geeks <button onclick="function()">Click me
        </button>
      </center> 
  </h1>
  
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
  </script>
    <script>
        (document).ready(function() {
            ("button").click(function() {
                alert($("p").text());
            });
        });
    </script>
  
    <p>GeeksforGeeks</p>
    <p>Jquery</p>
  
</body>
  
</html>
输出:
在点击按钮之前:

点击按钮后:。

例子-3:使用一个函数设置文本。
<!DOCTYPE html>
<html>
  
<body>
    <h1>
      <center>
      Geeks <button onclick="function()">Click me
        </button>
      </center>
  </h1>
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
  </script>
    
    <script>
        (document).ready(function() {
            ("button").click(function() {
                $("p").text(function(n) {
                return "Index No. of Element: " + n;
                });
            });
        });
    </script>
    
    <p>GeeksforGeeks</p>
    <p>Jquery_textmethod()</p>
  
</body>
  
</html>
输出:
在点击按钮之前:

点击按钮后:。

极客教程