HTML Get

jQuery庫包含了很多用來改變和操作HTML元素及其屬性的方法。

其中一個非常重要的部分就是jQuery可以用來操作DOM。

本篇介紹使用jQuery來取得DOM節點元素的值或屬性。

其中三個簡單而有用的方法如下:

 

text() – 設置或取得指定元素的文本內容。

html() – 設置或取得指定元素的內容(包括HTML標記)

val() – 設置或取得表單某個輸入域的值。

例如,下面代碼使用html()和text()方法取得HTML元素的內容:

 

 

[javascript] 

$("#btn1").click(function(){  

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

});  

$("#btn2").click(function(){  

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

});  

 

$("#btn1").click(function(){

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

});

$("#btn2").click(function(){

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

});

 

下面的代碼取得Form中Input 的內容:

 

 

 

[javascript]  

$("#btn1").click(function(){  

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

});  

 

$("#btn1").click(function(){

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

});

 

除了上面的方法外,attr()方法用來取得某個元素的屬性:

下面代碼用來取得鏈接的href屬性:

 

 

 

[html] 

<!DOCTYPE html>  

<html>  

<head>  

<meta charset="utf-8">  

<title>JQuery Demo</title>  

<script src="scripts/jquery-1.9.1.js"></script>  

</script>  

<script>  

    $(document).ready(function () {  

        $("button").click(function () {  

            alert($("#guidebee").attr("href"));  

        });  

    });  

</script>  

</head>  

  

<body>  

<p><a  

    href="http://www.imobilebbs.com"  

    id="guidebee">  

    imobilebbs.com  

   </a></p>  

<button>Show href Value</button>  

</body>  

</html>  

 

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>JQuery Demo</title>

<script src="scripts/jquery-1.9.1.js"></script>

</script>

<script>

    $(document).ready(function () {

        $("button").click(function () {

            alert($("#guidebee").attr("href"));

        });

    });

</script>

</head>

 

<body>

<p><a

    href="http://www.imobilebbs.com"

    id="guidebee">

    imobilebbs.com

   </a></p>

<button>Show href Value</button>

</body>

</html>

 

20130308001

原文鏈接:http://www.2cto.com/kf/201303/195084.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章