jQuery 取值、赋值的基本方法整理

这篇文章主要介绍了jQuery 取值、赋值的基本方法,需要的朋友可以参考下

/*获得TEXT.AREATEXT的值*/ 

 var textval = $("#text_id").attr("value"); 

 //或者 

 var textval = $("#text_id").val(); 

 /*获取单选按钮的值*/ 

 var valradio = $("input[@type=radio][@checked]").val(); 

 /*获取一组名为(items)的radio被选中项的值*/ 

 var item = $('input[@name=items][@checked]').val(); 

 /*获取复选框的值*/ 

 var checkboxval = $("#checkbox_id").attr("value"); 

 /*获取下拉列表的值*/ 

 var selectval = $('#select_id').val(); 


 //文本框,文本区域: 

 $("#text_id").attr("value",'');//清空内容 

 $("#text_id").attr("value",'test');//填充内容 

 //多选框checkbox: 

 $("#chk_id").attr("checked",'');//使其未勾选 

 $("#chk_id").attr("checked",true);//勾选 

 if($("#chk_id").attr('checked')==true) //判断是否已经选中 


 //单选组radio: 


 $("input[@type=radio]").attr("checked",'2');//设置value=2的项目为当前选中项 


 //下拉框select: 

 $("#select_id").attr("value",'test');//设置value=test的项目为当前选中项 

 $("<option value='test'>test</option><option value='test2'>test2</option>").appendTo("#select_id")//添加下拉框的option 

 $("#select_id").empty();//清空下拉框 


 获取一组名为(items)的radio被选中项的值 

 var item = $('input[@name=items][@checked]').val();//若未被选中 则val() = undefined 

 获取select被选中项的文本 

 var item = $("select[@name=items] option[@selected]").text(); 

 select下拉框的第二个元素为当前选中值 

 $('#select_id')[0].selectedIndex = 1; 

 radio单选组的第二个元素为当前选中值 

 $('input[@name=items]').get(1).checked = true; 


 //重置表单 

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

 .reset(); 

 });



1. 选取元素
$(”#myid”)效果等于document.getElementById(”myid”), 但是写的字符要少好多啊.

如果需要将jquery对象转换成html元素, 则只需要取其第0个元素即可. 例如$(”#myid”)返回的是jQuery对象, 而$(”#myid”)[0]返回的就是html元素

如果选择所有的img元素, 那么这么写: $(”img”)

如果选择带有class=”TextBox”的div元素(<div class=”TextBox”></div>), 那么这么写: $(”div.TextBox”)

选择带有myattr属性的元素$(”div[myattr]”)
选择带有myattr属性, 并且属性值等于myclass的元素$(”div[myattr='myclass']”)
属性不等于[myattr!='myclass']
属性以my开头[myattr^='my']
属性以class结尾[myattr$='class']
属性包含cla这三个字符[myattr*='cla']

如果一个选择会返回多个元素, 并且希望每返回一个元素, 就把某些属性应用到该元素上, 可以这么写

$(”div”).each(function() 

 { 

 $(this).css(”background-color”, “#F00″); 

 alert($(this).html()); 

 $(this).width(”200px”); 

 });



2.事件
给页面加onload事件处理方法

$(function() 

 { 

 alert(”页面结构加载完毕, 但是可能某些图片尚未加载(一般情况下, 此事件就够用了)”); 

 }); 


 可以给页面绑定多个onload事件处理方法 

 $(function() 

 { 

 alert(”我首先被执行”); 

 }); 


 $(function() 

 { 

 alert(”我第二被执行”); 

 }); 


 绑定特殊事件 

 $(”#myid”).keydown(function() 

 { 

 alert(”触发了keydown事件”); 

 });



除了这些常用的, 不常用的事件需要通过bind方法绑定

3. 元素属性/方法
得到一个元素的高度, $(”#myid”).height()
得到一个元素的位置, $(”#myid”).offset() 返回的是一个offset对象, 如果取元素位置的top, 则$(”#myid”).offset().top,?取left则$(”#myid”).offset().left
得到一个元素的innerHTML, $(”#myid”).html()
得到一个元素的innerText, $(”#myid”).text()
得到一个文本框的值, $(”#myid”).val()
得到一个元素的属性, $(”#myid”).attr(”myattribute”)

以上这些方法有个基本特征, 就是不带参数表示取值, 带有参数表示设定值(除了offset), 例如
$(”#myid”).height(”20″);
$(”#myid”).html(”<a href=”>asdasd</a>”)
$(”#myid”).val(”asdasd”)

需要注意, offset是只读的.

给一个元素设置属性 $(”#myid”).attr(”width”, “20%”)
读取一个属性 $(”#myid”).attr(”width”)
一次指定多个属性 $(”#myid”).attr({disabled: “disabled”, width:”20%”, height: “30″})
删除属性$(”#myid”).removeAttr(”disabled”)

应用样式$(”#myid”).addClass(”myclass”)
删除样式$(”#myid”).removeClass(”myclass”)

加一个样式$(”#myid”).css(”height”, “20px”)
加一组样式$(”#myid”).css({height:”20px”, width:”100px”})
需要注意的是: 如果是加一个样式, 这个样式的名字是css中的名字, 比如说style=”background-color:#FF0000″, 对应的jQuery写法是$(”#myid”).css(”background-color”, “#FF0000″)
但是加一组样式的时候, 样式的名字就是javascript中的css名字了, 比如: myid.style.backgroundColor = “#FF0000″, 对应的jQuery写法是$(”#myid”).css({backgroundColor:”#FF0000″})

4. 根据关系查找元素
找和自己同级的下一个元素$(”#myid”).next()
找和自己同级的所有位于自己之下的元素$(”#myid”).nextAll()
找和自己同级的上一个元素$(”#myid”).prev()
找和自己同级的所有位于自己之上的所有元素$(”#myid”).prevAll()
找自己的第一代子元素$(”#myid”).children()
找自己的第一个父元素$(”#myid”).parent()
找自己的所有父元素$(”#myid”).parents()
例子:
$(”div.l4″).parents().each(
function() {
alert($(this).html());
});

会把class=l4的div的所有父元素都得到, 并且alert出他们的html

例子:
$(”div.l4″).parents(”div.l2″).each(function() { alert($(this).html()); });
会得到class=l4的父元素, 该父元素必须是div, 而且其class=l2

这里说的所有方法, 都可以带表达式, 表达式的写法参考第一部分

5. 维护元素
在body中增加一个元素
$(”body”).append(”<input type='text' value='asd' />”)
该语句会把这段html插入到body结束标签之前, 结果是<input type='text' value='asd' /></body>

$(”body”).prepend(”<input type='text' value='asd' />”)
该语句会把这段html插入到body开始标签之后, 结果是<body><input type='text' value='asd' />

6.AJAX
用get方法请求一个页面
$.get(”http://www.google.com”, “q=jquery”, function(data, status){alert(data)})
表示请求http://www.google.com, 参数是q, 参数的值是jquery, 请求结束后(不管成功还是失败)执行后面的function, 该function有两个固定参数, data和status, data是返回的数据, status是本次请求的状态

用post方法请求一个页面
$.post(……..) 参数同get方法

7.其他方法
$.trim(str) 将str前后空格去掉
$.browser 返回当前用户浏览器的类型
$.browser.version返回当前浏览器的版本

8. 插件
jQuery支持插件, http://jquery.com/plugins/上面有很多现成的插件, 也可以自己写
自己写插件, 请参考http://docs.jquery.com/Core/jQ.....end#object 和http://docs.jquery.com/Core/jQuery.extend#object

1,下拉框:
var cc1 = $(".formc select[@name='country'] option[@selected]").text(); //得到下拉菜单的选中项的文本(注意中间有空格)
var cc2 = $('.formc select[@name="country"]').val(); //得到下拉菜单的选中项的值
var cc3 = $('.formc select[@name="country"]').attr("id"); //得到下拉菜单的选中项的ID属性值
$("#select").empty();//清空下拉框//$("#select").html('');
$("<option value='1'>1111</option>").appendTo("#select")//添加下拉框的option
稍微解释一下:
1.select[@name='country'] option[@selected] 表示具有name 属性,
并且该属性值为'country' 的select元素 里面的具有selected 属性的option 元素;
可以看出有@开头的就表示后面跟的是属性。

2,单选框:
$("input[@type=radio][@checked]").val(); //得到单选框的选中项的值(注意中间没有空格)
$("input[@type=radio][@value=2]").attr("checked",'checked'); //设置单选框value=2的为选中状态.(注意中间没有空格)

3,复选框:

$("input[@type=checkbox][@checked]").val(); //得到复选框的选中的第一项的值 

 $("input[@type=checkbox][@checked]").each(function(){ //由于复选框一般选中的是多个,所以可以循环输出 

 alert($(this).val()); 

 }); 


 $("#chk1").attr("checked",'');//不打勾 

 $("#chk2").attr("checked",true);//打勾 

 if($("#chk1").attr('checked')==undefined){} //判断是否已经打勾 


 charAt(n): Returns the character at the specified index in a string. The index starts from 0. 

 1     var str = "JQUERY By Example"; 

 2     var n = str.charAt(2) 

 3        

 4     //Output will be "U" 



 charCodeAt(n): Returns the Unicode of the character at the specified index in a string. The index starts from 0. 

 1     var str = "HELLO WORLD"; 

 2     var n = str.charCodeAt(0); 

 3        

 4     //Output will be "72" 



 concat(string1, string2, .., stringX): The concat() method is used to join two or more strings. This method does not change the existing strings, but returns a new string containing the text of the joined strings. 

 1     var str1 = "jQuery "; 

 2     var str2 = "By Example!"; 

 3     var n = str1.concat(str2); 

 4        

 5     //Output will be "jQuery By Example!" 



 fromCharCode(n1, n2, ..., nX): Converts Unicode values into characters. This is a static method of the String object, and the syntax is always String.fromCharCode(). 

 1     var n = String.fromCharCode(65); 

 2        

 3     //Output will be "A" 



 indexOf(searchvalue, [start]): Returns the position of the first occurrence of a specified value in a string. This method returns -1 if the value to search for never occurs. This method is case sensitive! 

 1     var str="Hello world, welcome to the my blog."; 

 2     var n=str.indexOf("welcome"); 

 3        

 4     //Output will be "13" 



 lastIndexOf(searchvalue, [start]): Returns the position of the last occurrence of a specified value in a string. The string is searched from the end to the beginning, but returns the index starting at the beginning, at postion 0. Returns -1 if the value to search for never occurs. This method is case sensitive! 

 1     var str="Hello planet earth, you are a great planet."; 

 2     var n=str.lastIndexOf("planet"); 

 3        

 4     //Output will be "36" 



 substr(start, [length]): The substr() method extracts parts of a string, beginning at the character at the specified posistion, and returns the specified number of characters. 

 1     var str="Hello world!"; 

 2     var n=str.substr(2,3) 

 3        

 4     //Output will be "llo" 



 substring(from, [to]): The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string. This method extracts the characters in a string between "from" and "to", not including "to" itself. 

 1     var str="Hello world!"; 

 2     var n=str.substring(2,3) 

 3        

 4     //Output will be "l" 



 toLowerCase(): The toLowerCase() method converts a string to lowercase letters. 

 1     var str="HELLO WoRld!"; 

 2     str = str.toLowerCase(); 

 3     //Output will be "hello world!" 



 toUpperCase(): The toUpperCase() method converts a string to uppercase letters. 

 1     var str="hello WoRLd!"; 

 2     str = str.toUpperCase(); 

 3     //Output will be "HELLO WORLD!"



1.去掉空格  
 
var txt=$.trim($("txt1").val());  

2.转为数字  
 
 txtNum=Number($.trim(txt)) + 1;  
 
var thisEle = $("#para").css("font-size"); //获取字体大小  
var textFontSize = parseFloat(thisEle , 10);  
 
 3.四舍五入为整数/随机数  
 
Math.ceil()  
ceil() 方法可对一个数进行上舍入。  
参数必须是一个数值。返回值大于等于 x,并且与它最接近的整数。  
Math.floor()  
floor() 方法可对一个数进行下舍入。  
参数可以是任意数值或表达式。返回值小于等于 x,且与 x 最接近的整数。  
Math.round()  
round() 方法可把一个数字舍入为最接近的整数  
参数必须是一个数值。返回值与 x 最接近的整数。  
 
Math.ceil(4.8992303)        输出结果:5  
Math.floor(4.8992303)      输出结果:4  
Math.round(4.8992303)    输出结果:5  
Math.ceil(4.29993354)      输出结果:5  
Math.floor(4.29993354)    输出结果:4  
Math.round(4.29993354)  输出结果:4   
Math.round(Math.random()*100); //产生0-100的随机数  
   
4.截取字符串  
 
var txt=$("p").text().substr(0,15);//截取从首个字符开始的15个字符  
 
5.字符串替换  
 
$("image").attr("src").replace("size=60", "size=200"); //用法replace(要替换的目标,替换后新值)  
 
 配合正则替换 如: $("#txt").replace(/[^\d-]/g, "").replace(/^\-/g, "");  
 
6.分割字符串  
 

var str=new String();    

   

 var arr=new Array();    

   

 str="百度,农夫it站,谷歌,竹林风,nongfuit.com,网页交流群,180550045欢迎加入";    

   

 arr=str.split(',');//注split可以用字符或字符串分割   

   

 //alert(str.split(',')[1]);   

   

   

 for(var i=0;i<arr.length;i++)    

   

 {    

   

 alter(arr[i]);   

   

 }


 
    
7.js与jquery对象互相转换  
 

var aa = $("#mm").get(0); // jquery 对象转成 js 对象   

 var bb = $(aa);  //js 对象转成 jquery 对象   

   

     

   

 8.使用正则匹配   

   

 var matchTel = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;   

   

 if (!matchTel.test($("#txtTel").val())) {   

             alert("电话格式错误!");   

             return !1;   

         }   


 9.Ajax Autocomplete: 


 $( "#tags" ).autocomplete({ 

             source: function( request, response ) { 

                 $.ajax({ 

                     url: "sql/sqlgetWebsqlDataBaseInforAjax", 

                     dataType: "json", 

                     data:{ 

                         searchDbInforItem: request.term 

                     }, 

                     success: function( data ) { 

                         response( $.map( data, function( item ) { 

                             return { 

                                 dbId:item.dbid, 

                                 jdbcUrl:item.jdbcUrl, 

                                 ip:item.ip, 

                                 port:item.port, 

                                 sch:item.sch, 

                                 username: item.username, 

                                 password:item.password, 

                                 value: item.labelview 

                             } 

                         })); 

                     } 

                 }); 

             }, 

             minLength: 1, 

             select: function( event, ui ) { 

                 $("#dbInforDdId").val(ui.item.dbId); 

                 $("#dbInforDdjdbcUrl").val(ui.item.jdbcUrl); 

                 $("#dbInforIp").val(ui.item.ip); 

                 $("#dbInforPort").val(ui.item.port); 

                 $("#dbInforSch").val(ui.item.sch); 

                 $("#dbInforUserName").val(ui.item.username); 

                 $("#dbInforPassword").val(ui.item.password); 

             } 

         }); 


 ---------- 

         var cache = {}; 

         $( "#tags" ).autocomplete({ 

             source: function(request, response ) { 

                 var term = request.term; 

                 if ( term in cache ) { 

                     response( $.map( cache[ term ], function( item ) { 

                         return { 

                             dbId:item.dbid, 

                             jdbcUrl:item.jdbcUrl, 

                             ip:item.ip, 

                             port:item.port, 

                             sch:item.sch, 

                             username: item.username, 

                             password:item.password, 

                             value: item.labelview 

                         } 

                     })); 

                     return; 

                 } 

                 $.ajax({ 

                     url: "sql/sqlgetWebsqlDataBaseInforAjax", 

                     dataType: "json", 

                     data:{ 

                         searchDbInforItem: request.term 

                     }, 

                     success: function( data ) { 

                         cache[ term ] = data; 

                         response( $.map( data, function( item ) { 

                             return { 

                                 dbId:item.dbid, 

                                 jdbcUrl:item.jdbcUrl, 

                                 ip:item.ip, 

                                 port:item.port, 

                                 sch:item.sch, 

                                 username: item.username, 

                                 password:item.password, 

                                 value: item.labelview 

                             } 

                         })); 

                     } 

                 }); 

             }, 

             minLength: 1, 

             select: function( event, ui ) { 

                 $("#dbInforDdId").val(ui.item.dbId); 

                 $("#dbInforDdjdbcUrl").val(ui.item.jdbcUrl); 

                 $("#dbInforIp").val(ui.item.ip); 

                 $("#dbInforPort").val(ui.item.port); 

                 $("#dbInforSch").val(ui.item.sch); 

                 $("#dbInforUserName").val(ui.item.username); 

                 $("#dbInforPassword").val(ui.item.password); 

             } 

         }); 

 ------------------ 

 window.οnlοad=function(){   

         $(".rph").autocomplete({   

                minLength: 0,   

                source: function( request, response ) {   

                    $.ajax({   

                         url : "/fftg/redisPh/getRedisPharmacy",   

                         type : "post",   

                         dataType : "json",   

                         data : {"phName":$(".rph").val()},   

                            

                        success: function( data ) {   

                              console.log(data);   

                              response( $.map( data, function( item ) {   

                                    return {   

                                      label: item.label,   

                                      value: item.value   

                                    }   

                              }));   

                        }   

                   });   

                },   

                focus: function( event, ui ) {   

                    $(".rph").val( ui.item.label );   

                    $("#rpId").val( ui.item.value );   

                      return false;   

                    },   

                select: function( event, ui ) {   

                    $(".rph").val( ui.item.label );   

                    $("#rpId").val( ui.item.value );   

                    return false;   

                }   

             });   

     }