jQuery data()方法和HTML5 data-*自定義屬性

antzone發表於2017-04-18

data()方法可以參閱jQuery data()方法一章節。

data-*可以參閱HTML5的data-*自定義屬性用法一章節。

下面就介紹一下如何利用data()方法來讀取自定義屬性。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title>
<style>
#antzone{
  width:200px;
  height:100px;
  background:#ccc;
  line-height:100px;
  text-align:center;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
  $("input").click(function(){
    var url=$("#antzone").data("url");
    $("#antzone").text(url);
  })
});
</script> 
</head> 
<body> 
<div id="antzone" data-url="www.softhwy.com"></div>
<input type="button" value="檢視效果"/>
</body> 
</html>

上面能夠讀取自定義屬性的值,屬性名稱不帶"data-"。

相關文章