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

JQuery学习

2013-08-28 15:11 309 查看
1.jQuery元素选择器

语法    描述

$(this)      当前 HTML 元素

$("p")            所有 <p> 元素

$("p.intro")    所有 class="intro" 的 <p> 元素

$(".intro")    所有 class="intro" 的元素

$("#intro")    id="intro" 的第一个元素

$("ul li:first")    每个 <ul> 的第一个 <li> 元素

$("[href$='.jpg']")    所有带有以 ".jpg" 结尾的属性值的 href 属性

$("div#intro .head")    id="intro" 的 <div> 元素中的所有 class="head" 的元素

$("p").css("background-color","red");

2.文档就绪函数$(document).ready

所有 jQuery 函数位于一个 document ready 函数中:

$(document).ready(function(){

--- jQuery functions go here ----

});

这是为了防止文档在完全加载(就绪)之前运行 jQuery 代码。

eg:

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

$(document).ready(function(){

  $("button").click(function(){

    $("p").hide();

  });

});

</script>

</head>

<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<button>Click me</button>

</body>

</html>

3.jQuery 名称冲突

jQuery 使用 $ 符号作为 jQuery 的简介方式。

某些其他 JavaScript 库中的函数(比如 Prototype)同样使用 $ 符号。

jQuery 使用名为 noConflict() 的方法来解决该问题。

var jq=jQuery.noConflict(),帮助您使用自己的名称(比如 jq)来代替 $ 符号。

eg:<!DOCTYPE html>

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script>

$.noConflict();

jQuery(document).ready(function(){

  jQuery("button").click(function(){

    jQuery("p").text("jQuery 仍在运行!");

  });

});

</script>

</head>

<body>

<p>这是一个段落。</p>

<button>测试 jQuery</button>

</body>

</html>

4.jQuery 事件

$(document).ready(function)    将函数绑定到文档的就绪事件(当文档完成加载时)

$(selector).click(function)    触发或将函数绑定到被选元素的点击事件

$(selector).dblclick(function)    触发或将函数绑定到被选元素的双击事件

$(selector).focus(function)    触发或将函数绑定到被选元素的获得焦点事件

$(selector).mouseover(function)    触发或将函数绑定到被选元素的鼠标悬停事件

5.jQuery获取

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

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

val()-设置或返回表单字段的值

attr()-获取属性值

var txt = $("#span1").text();//兼容火狐和IE获取span的值,火狐var txt =

document.getElementById("span1").innerHtml()获取不到值

document.getElementById("lblID").innerHTML;//label解析为html即为一个span,没有value属性,所

以可以用innerHTML或innerText
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: