jQuery text()方法示例

时间:2020-02-23 14:46:15  来源:igfitidea点击:

在本教程中,我们将看到jQuery文本方法示例。

文本方法用于获取所有匹配元素的文本,text("新文")用于为所有匹配元素设置文本。

text()语法:

$("selectors").text() 
Example :
$("div").text();

text('new text')语法:

$("selectors").text('new text')
Example:
 $("div").text('this text is being set by text method');

让我们通过示例来理解:

<!doctype>
<html>
<head>
  <title>Jquery text method example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery text method example</h2>
<style>
.blackBorder{
        border:4px dotted black;
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#textButton").click(function(){
         alert($("div").text()) ;
      });
$("#setTextButton").click(function(){
         $("div").text('this text is being set by text() method');
      });
$("#reset").click(function(){
         location.reload();
   });
 });
 
</script>
<body>
  <button id="textButton">Using text</button>
  <button id="setTextButton">Using text('new text') </button>
<button id="reset">Reset</button>
<br 
<div class='blackBorder'>
 Hello world from theitroad!!!!
   </div>
<br
<div class='blackBorder' >
 Welcome to JQuery.
  </div>
</body>
</html>