Jquery笔记之第二天

来源:互联网 发布:mac for 百度云 编辑:程序博客网 时间:2024/05/19 13:27

Jquery笔记之第二天

jQuery - 获取内容和属性

获得内容 - text()、html() 以及 val()

<script>$(document).ready(function(){  $("#btn1").click(function(){    alert("Text: " + $("#test").text());  });  $("#btn2").click(function(){    alert("HTML: " + $("#test").html());  });});</script>
$("button").click(function(){  alert($("#runoob").attr("href"));});

设置内容 - text()、html() 以及 val()

<script>$(document).ready(function(){  $("#btn1").click(function(){    $("#test1").text("Hello world!");  });  $("#btn2").click(function(){    $("#test2").html("<b>Hello world!</b>");  });  $("#btn3").click(function(){    $("#test3").val("RUNOOB");  });});</script>

添加新的 HTML 内容

我们将学习用于添加新内容的四个 jQuery 方法:

  • append() - 在被选元素的结尾插入内容
  • prepend() - 在被选元素的开头插入内容
  • after() - 在被选元素之后插入内容
  • before() - 在被选元素之前插入内容
$("img").after("在后面添加文本"); $("img").before("在前面添加文本");
<script>function afterText(){var txt1="<b>I </b>";                    // 使用 HTML 创建元素var txt2=$("<i></i>").text("love ");     // 使用 jQuery 创建元素var txt3=document.createElement("big");  // 使用 DOM 创建元素txt3.innerHTML="jQuery!";$("img").after(txt1,txt2,txt3);          // 在图片后添加文本}</script>

删除元素/内容

<script>$(document).ready(function(){  $("button").click(function(){    $("#div1").remove();  });});</script>
<script>$(document).ready(function(){  $("button").click(function(){    $("#div1").empty();  });});</script>
<script>$(document).ready(function(){  $("button").click(function(){    $("p").remove(".italic");//过滤  });});</script>

jQuery - 获取并设置 CSS 类

jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:

  • addClass() - 向被选元素添加一个或多个类
  • removeClass() - 从被选元素删除一个或多个类
  • toggleClass() - 对被选元素进行添加/删除类的切换操作
  • css() - 设置或返回样式属性
<script>$(document).ready(function(){  $("button").click(function(){    $("h1,h2,p").addClass("blue");    $("div").addClass("important");  });});</script><style type="text/css">.important{font-weight:bold;font-size:xx-large;}.blue{color:blue;}</style>

<script>$(document).ready(function(){  $("button").click(function(){    $("h1,h2,p").removeClass("blue");  });});</script><style type="text/css">.important{font-weight:bold;font-size:xx-large;}.blue{color:blue;}</style>

<script>$(document).ready(function(){  $("button").click(function(){    $("h1,h2,p").toggleClass("blue");  });});</script><style type="text/css">.blue{color:blue;}</style>
CSS方法
<script>$(document).ready(function(){  $("button").click(function(){alert("背景颜色 = " + $("p").css("background-color"));
$("p").css("background-color","yellow");
$("p").css({"background-color":"yellow","font-size":"200%"});  });});</script>
0 0
原创粉丝点击