jQuery实现对P标签的操作

来源:互联网 发布:淘宝原图制作方法 编辑:程序博客网 时间:2024/06/10 00:58

注:以下代码均通过W3School在线测试。

根据id获取元素本身(Object对象)的方法:

$("#id");

例如:

<!DOCTYPE html><html><head><script src="/jquery/jquery-1.11.1.min.js"></script><script>$(document).ready(function(){  $("p").click(function(){    alert($("#p1"));  });});</script></head><body><p id="p1" name="name1">如果您点击我,我会消失。</p><p id="p2" name="name2">点击我,我会消失。</p><p id="p3" name="name3">也要点击我哦。</p></body></html>

运行的结果:



根据class获取元素本身(Object)的方法:

<!DOCTYPE html><html><head><script src="/jquery/jquery-1.11.1.min.js"></script><script>$(document).ready(function(){  $("p").click(function(){    alert("根据class类获取元素本身:"+$(".class1"));  });});</script></head><body><p id="p1" name="name1" class="class1">如果您点击我,我会消失。</p><p id="p2" name="name2" class="class2">点击我,我会消失。</p><p id="p3" name="name3" class="class3">也要点击我哦。</p></body></html>

运行的结果:



获取P标签文本内容的方法:

方法一:$("#p1").text();

方法二:$("#p1").html();

例如:

<!DOCTYPE html><html><head><script src="/jquery/jquery-1.11.1.min.js"></script><script>$(document).ready(function(){  $("p").click(function(){    alert("text()方法:"+$("#p1").text());    alert("html()方法:"+$("#p1").html());  });});</script></head><body><p id="p1" name="name1">如果您点击我,我会消失。</p><p id="p2" name="name2">点击我,我会消失。</p><p id="p3" name="name3">也要点击我哦。</p></body></html>

运行的结果:

$("#p1").text();方法:



$("#p1").html();方法:



获取属性的方法:

$(this).attr("id")
例如:

<!DOCTYPE html><html><head><script src="/jquery/jquery-1.11.1.min.js"></script><script>$(document).ready(function(){  $("p").click(function(){    alert("P标签中的name属性值:"+$(this).attr("name"));    alert("P标签中的class属性值:"+$(this).attr("class"));    alert("P标签中的id属性值:"+$(this).attr("id"));  });});</script></head><body><p id="p1" name="name1" class="class1">如果您点击我,我会消失。</p><p id="p2" name="name2" class="class2">点击我,我会消失。</p><p id="p3" name="name3" class="class3">也要点击我哦。</p></body></html>

运行的结果:

获取name属性:



获取class属性:



获取id属性:












0 0