jQuery 之 获取页面内容和属性(六)

素颜马尾好姑娘i 2022-09-23 13:48 272阅读 0赞

获得内容 - text()、html() 以及 val()

三个简单实用的用于 DOM 操作的 jQuery 方法:

text() - 设置或返回所选元素的文本内容

html() - 设置或返回所选元素的内容(包括 HTML 标记)

val() - 设置或返回表单字段的值

===========================================================

下面的例子演示如何通过 jQuery text() 和 html() 方法来获得内容:

实例

$(“#btn1”).click(function(){

alert(“Text: “ + $(“#test”).text());

});

$(“#btn2”).click(function(){

alert(“HTML: “ + $(“#test”).html());

});

下面的例子演示如何通过 jQuery val() 方法获得输入字段的值:

实例

$(“#btn1”).click(function(){

alert(“Value: “ + $(“#test”).val());

});

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
  5. </script>
  6. <script>
  7. $(document).ready(function(){
  8. $("button").click(function(){
  9. alert("Value: " + $("#test").val());
  10. });
  11. });
  12. </script>
  13. </head>
  14. <body>
  15. <p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
  16. <button>Show Value</button>
  17. </body>
  18. </html>

===========================================================

获取属性 - attr()

jQuery attr() 方法用于获取属性值。

下面的例子演示如何获得链接中 href 属性的值:

实例

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
  5. </script>
  6. <script>
  7. $(document).ready(function(){
  8. $("button").click(function(){
  9. alert($("#w3s").attr("href"));
  10. });
  11. });
  12. </script>
  13. </head>
  14. <body>
  15. <p><a href="http://www.w3cschool.cc" id="w3s">W3Cschool.cc</a></p>
  16. <button>Show href Value</button>
  17. </body>
  18. </html>

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读