本文已参与「新人创作礼」活动,一起开启掘金创作之路。
获取内容的三种方法:
text():设置或者返回元素文本内容
html():设置或者返回所选的元素内容(包含html标记)
val():返回表单值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取元素</title>
<style>
p{
border: 1px solid black;
}
div{
border: 1px solid black;
}
a{
display: block;
}
</style>
</head>
<body>
<p>这是一个p标签 <a href="#">一个a</a></p>
<div>这是一个div标签 <a href="#">第二个a</a></div>
<br>
<input type="text" name="" value="111" id="">
<a href="https://www.baidu.com" id="a1">HTML 元素我们自己自定义的 DOM 属性,在处理时,使用 attr 方法</a>
<a href="https://www.baidu.com" id="a2">HTML 元素本身就带有的固有属性,在处理时,使用 prop 方法</a>
<script src="../jquery-3.6.0.js"></script>
<script>
$(document).ready(function(){
$('p').click(function(){
alert($('p').text()); //text()
})
$('div').click(function(){
alert($('div').html()); //html()
})
$('input').click(function(){
alert($('input').val()); //val()
})
$('#a1').click(function(){
alert($('#a1').attr('href')); //attr获取自定义属性
})
$('#a2').click(function(){
alert($('#a2').prop('href')); //prop获取固定属性
})
})
</script>
</body>
</html>
text():获取返回元素的文本
html():返回所选元素中的的所有内容
val():返回表单值
获取自定义的DOM属性:attr()
获取本身自带的固定属性:prop()
注:
prop()函数的结果:
1.如果有相应的属性,返回指定属性值。
2.如果没有相应的属性,返回值是空字符串。
attr()函数的结果:
1.如果有相应的属性,返回指定属性值。
2.如果没有相应的属性,返回值是 undefined。