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

来源:互联网 发布:淘宝联盟怎么玩 编辑:程序博客网 时间:2024/06/06 02:12

获得内容 - 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());

});

<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script><script>$(document).ready(function(){  $("button").click(function(){    alert("Value: " + $("#test").val());  });});</script></head><body><p>Name: <input type="text" id="test" value="Mickey Mouse"></p><button>Show Value</button></body></html>
===========================================================

获取属性 - attr()

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

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

实例

<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script><script>$(document).ready(function(){  $("button").click(function(){    alert($("#w3s").attr("href"));  });});</script></head><body><p><a href="http://www.w3cschool.cc" id="w3s">W3Cschool.cc</a></p><button>Show href Value</button></body></html>


0 0
原创粉丝点击