---
title: "(一)jQuery总结：attribute"
author: "y8820960"
date: "2012-08-16T16:40:21Z"
tags: []
categories: ["Web前端"]
slug: "jquery-attribute"
draft: false
lastmod: "2012-08-24T15:13:23Z"
id: 1634110
url: "https://marvel00000.iteye.com/blog/1634110"
---

**attribute** ：

$("p").addClass(css中定义的样式类型);  给某个元素添加样式

$("img").attr({src:"test.jpg",alt:"test Image"});  给某个元素添加属性/值，参数是map

$("img").attr("src","test.jpg");  给某个元素添加属性/值，getter、setter类型

$("img").attr("title",function(){return this.src});  给某个元素添加属性/值

$("元素名称").html();  获得该元素内的内容(元素，文本等)

$("元素名称").html("&lt;b&gt;new stuff&lt;/b&gt;");给某元素设置内容

$("元素名称").removeAttr("属性名称");   给某元素删除指定的属性以及属性值

$("元素名称").removeClass("class");  给某元素删除指定的样式

$("元素名称").text();  获得该元素的文本

$("元素名称").text(value); 设置该元素的文本值为value

$("元素名称").toggleClass(class)   当元素存在参数中的样式的时候取消，如果不存在就设置此样式

$("input 元素名称").val();  获得input元素的值

$("input 元素名称").val(value);  设置input元素的值为value

 

 

**Manipulation:**

$("元素名称").after(content);  在匹配元素后面添加内容

$("元素名称").append(content); 将 content 作为元素的内容插入到该元素的后面

$("元素名称").appendTo(content);  在content后街元素

$("元素名称").before(content);  与after方法相反

$("元素名称").clone(布尔表达式);  当布尔表达式为真时，克隆元素(无参时，当true处理)

$("元素名称").empty();  将该元素的内容置为空

$("元素名称").insertAfter(content);  将该元素插入到content之后

$("元素名称").insertBefore(content);  将该元素插入到content之前

$("元素").prepend(content);  将content作为该元素的一部分，放到该元素的最前面

$("元素").prependTo(content);  将该元素作为content的一部分，放在content的最前面

$("元素").remove();  删除所有的指定元素

$("元素").remove("exp"):  删除所有包含exp的元素

$("元素").wrap("html");  用html来包围该元素

$("元素").wrap(element);  用element来包围该元素

 

**Traversing(穿越 ):**

add(expr)

add(html)

add(elements)

children(expr)

contains(str)

end()

filter(expression)

filter(filter)

find(expr)

is(expr)

next(expr)

not(el)

not(expr)

not(elems)

parent(expr)

prev(expr)

siblings(expr)

 

 

**Core:**

 

$(html).appendTo("body");  相当于在body中写了一段html代码

$(elems)  获得DOM上的某个元素

$(function(){......}) ;  执行一个函数

$("div &gt; p").css("border", "1px solid gray");  查找所有div的子节点p，添加样式

$("input:radio",document.form\[0]) 在当前页面的第一个表单中查找所有的单选按钮

$.extend(prop)  prop是一个jquery对象

举例：

jQuery.extend({

  min:function(a,b) {return a&lt;b ? a : b};

  max:function(a,b){return a&gt;b ? a : b};

});

jQuery(expression,\[context])-$(expression,\[context]);在默认情况下，$()查询的事当前HTML的DOM元素。

each(callback)  以每一个匹配的元素作为上下文来执行一个函数

举例1：

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

  $("li").each(function(){

    $(this).toggleClass("example");

});

});

举例2：

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

  $("div").each(function(index,domEle){

    // domEle == this

    $(domEle).css("backgroundColor","yellow");

    if($(this).is("#stop")){

      $("span").text("Stopped at div index #" + index);

      return false;

}

})

})