您的位置:首页 > Web前端 > JQuery

JQuery获取元素的值与属性

2016-02-04 11:48 639 查看
四个简单实用的用于 DOM 操作的 jQuery 方法:

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

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

val() - 设置/返回表单元素的value值;

attr()- 设置/返回元素的某一属性值。

返回例子:

<!DOCTYPE html>

<html>

<head>

<script src="/jquery/jquery-1.11.1.min.js"></script>

<script>

$(document).ready(function(){

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

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

  });

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

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

  });

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

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

  });

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

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

  });

});

</script>

</head>

<body>

<p id="test" class="class">请输入你的<b style="color:red">名字</b>:

<input type="text" id="input" value="Michael">

</p>

<button id="button1">显示文本</button>

<button id="button2">显示 HTML</button>

<button id="button3">显示Value</button>

<button id="button4">显示id属性的值</button>

</body>

</html>

若要设置则在括号内写入相应的即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: