---
title: "八、属性操作"
author: "youyang_java"
date: "2013-04-02T22:06:41Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-04-18T16:30:16Z"
id: 1841065
url: "https://youyang-java.iteye.com/blog/1841065"
---

$(function() {  
            $("tbody tr").each(function(n){  
                //使用attr只加入一个参数可以获取属性值  
                //alert($(this).attr("id"));  
                 
                //通过attr()设置两个参数，可以完成对某个节点的属性的设置  
                // $(this).attr("title",$(this).children("td:eq(1)").html());  
                 
                //可以基于json的格式来设置属性,甚至可以设置一些非html的属性，通过这些属性来做一些特殊处理  
                //但是设置特殊属性的这种方式在jquery1.4之后就基本不使用，因为在1.4之后提供data方法  
                $(this).attr({  
                    "title":$(this).children("td:eq(1)").html(),  
                    "id":$(this).children("td:eq(0)").html(),  
                    "personId":n  
                });  
                 
                //可以移除属性  
                // $("tr#2").removeAttr("personid");  
            });

 

    //设置所有a中以http为链接开头的超链接在新窗口打开  
    $("a\[href^='http://']").attr("target","\_blank");  
   

     //为属性设置一个函数  
    //设置tbody中的tr的title属性，让属性的值为第几个tr，函数中n为遍历中的索引  
    $("tbody tr").attr("title",function(n){  
        return "这是第"+(n+1)+"个tr";  
    });

 

        //可以将一些值存储在标签中，这个值不会通过属性的方式显示给用户  
        $("thead tr td:eq(0)").data("prop","id");//&lt;td prop="id"&gt;用户标识&lt;/td&gt;  
        $("thead tr td:eq(1)").data("prop","username");  
        $("thead tr td:eq(2)").data("prop","age");  
        $("thead tr td:eq(3)").data("prop","password");

});

 

 

一个小例子

&lt;script type="text/javascript"&gt;  
    $(function() {  
        $("#all").click(function(){  
            if($(this).prop("checked")) {  
                //选中  
                $("input\[type='checkbox']").prop("checked",true);  
                $(this).next("span").html("全取消");  
            } else {  
                $("input\[type='checkbox']").prop("checked",false);  
                $(this).next("span").html("全选");  
            }  
        });  
        $("#reverse").click(function(){  
            var c = $("input\[type='checkbox']:not(#all):checked");  
            var nc = $("input\[type='checkbox']:not(#all):not(:checked)");  
            c.prop("checked",false);  
            nc.prop("checked",true);  
        });  
    });  
     
&lt;/script&gt;

&lt;body&gt;  
    &lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;  
    &lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;&lt;input type="checkbox"/&gt;  
    &lt;br/&gt;  
    &lt;input type="checkbox" id="all"/&gt;&lt;span&gt;全选&lt;/span&gt;  
    &lt;input type="button" id="reverse" value="反选"/&gt;  
&lt;/body&gt;