jQuery針對各類元素操作基礎教程,jquery基礎教程

來源:互聯網
上載者:User

jQuery針對各類元素操作基礎教程,jquery基礎教程

本文執行個體講述了jQuery針對元素的操作,包括基礎操作、選擇要操作的元素及處理DOM元素等。對jQuery的學習有很好的借鑒價值。分享給大家供大家參考之用。具體分析如下:

1、基礎

jquery對象集:

$():jquery對象集合

擷取jquery對象集中的元素:

使用索引擷取封裝器中的javascript元素:

var temp = $('img[alt]')[0]

使用jquery的get方法擷取jquery對象集中的javascript元素:

var temp = $('img[alt]').get(0)

使用jquery的eq方法擷取jquery對象集中的jquery對象元素:

$('img[alt]').eq(0)
$('img[alt]').first()
$('img[alt]').last()

jquery對象集轉換成javascript數組:

var arr = $('label+button').toArray()

label後面所有同級button元素,轉換成javascript數組

jquery對象集的索引:
var n = $('img').index($('img#id')[0]) 注意:index()參數是javascript元素
var n = $('img').index('img#id') 等同於上一行 找不到返回-1
var n = $('img').index() 獲得img在同級元素中的索引

向jquery對象集中添加更多的jquery對象集:   
使用逗號:

$('img[alt],img[title]')

使用add方法:

$('img[alt]').add('img[title]')

對不同的jquery對象集中採取不同的方法:

$('img[alt]').addClass('thickBorder').add('img[title]').addClass('');

向jquery對象集中添加新建立的元素:

$('p').add('<div></div>');

刪除jquery對象集中的元素:

$('img[title]').not('[title*=pu]')$('img').not(function(){return !$(this).hasClass('someClassname')})

過濾jquery對象集:
$('td').filter(function(){return this.innerHTML.match(^\d+$)})過濾包含數位td

擷取jquery對象集的子集

$('*').slice(0,4) 包含前4個元素的新的jquery對象集
$('*').slice(4) 包含前4個元素的新的jquery對象集
$('div').has('img[alt]')

轉換jquery對象集中的元素:

var allIds = $('div').map(function(){ return (this.id==undefined) ? null : this.id;}).get();

上述樣本可通過get方法轉換成javascript數組。

遍曆jquery對象集中的元素:

$('img').each(function(n){ this.alt = '這是第['+n+']張圖片,圖片的id是' + this.id;})$([1,2,3]).each(function(){alert(this);})

使用元素間關係擷取jquery對象集:

$(this).closest('div')比如觸發的按鈕在哪個div中發生
$(this).siblings('button[title="Close"]')所有同級元素,不包含本身
$(this).children('.someclassname')所有子節點元素,不包含重複子節點
$(this).closest('')臨近祖先元素
$(this).contents()由元素內容組成的jquery對象集,比如可以擷取<iframe>元素內容
$(this).next('.someclassname')下一個同級元素
$(this).nextAll()後面所有的同級元素
$(this).nextUntil('.someclassname')後面所有的同級元素直到遇到目標元素
$(this).offsetParent()離jquery對象集最近的父輩元素
$(this).parent()直接父元素
$(this).parents()所有父元素
$(this).parrentsUntil()所有父元素,直到目標父元素
$(this).prev()上一個同級元素
$(this).prevAll()之前的所有同級元素
$(this).prevTntl()之前的所有同級元素,直到目標元素

其它擷取jquery對象集的方式:

$(this).find(p span)

判斷是否是某個jquery對象集:

var hasImg = $('*').is('img');

jquery方法:

$().hide()
$().addClass('')
$().html('')
$('a').size()元素數量

jquery選取器:

$('p:even')  
$('tr:nth-child(1)')
$('body > div')直接子項目
$('a[href=$='pdf']')根據屬性選擇
$(div:has(a))過濾

jquery函數:

$.trim()
jquery執行時間:
$(document).ready(function(){});
$(function(){});

建立DOM元素:

$('<p></p>').insertAfter();$('<img>',{ src: '', alt: '', title: '', click: function(){}}).css({ cursor:'pointer', border:'', padding:'', backgroundColor:'white'}).append('');

jquery擴充:

$.fn.disable = function(){ return this.each(function(){ if(this.disabled != null) this.disabled = true; })};$('').disable();

jquery測試元素是否存在:

if(item)(){}else{} 寬鬆測試
if(item != null) 推薦測試,能把null和undefined區別開

2、選擇要操作的元素

根據標籤名:$('a')  
根據id:$('#id')
根據類名:$('.someclassname')
滿足多個條件:$('a#id.someclassname') 或 $('div,span')
某個元素的所有子節點:$(p a.someclassname)
某個元素的直接子節點:$(ul.myList > li)
根據屬性名稱:
$(a[href^='http://']) 以...開頭
$(href$='.pdf')以...結尾
$(form[method])包含method屬性的form
$(intput[type='text'])
$(intput[name!=''])
$(href*='some')包含

某元素後的第一個元素:$(E+F)匹配的是F,F是E後面的第一個元素

某元素後的某一個元素:$(E~F)匹配的是F,F是E後面的某一個元素

通過位置:

$(li:first)第一個li
$(li:last)最後一個li
$(li:even)偶數行li
$(li:odd)奇數行li
$(li:eq(n))第n個元素,索引從0開始
$(li:gt(n))第n個元素之後的元素,索引從0開始
$(li:lt(n))第n個元素之前的元素,索引從0開始
$(ul:first-child)列表中的第一個li
$(ul:last-child)列表中的最後一個li
$(ul:nth-child(n))列表中的第n個li
$(ul:only-child)沒有兄弟li的ul
$(ul:nth-child(even))列表中的偶數行li,odd為計數行li
$(ul:nth-child(5n+1))列表中被5除餘1的li

通過過濾器:

$(input:not(:checkbox))
$(':not(img[src*="dog"])')
$('img:not([src*="dog"])')
$(div:has(span))
$('tr:has(img[src$="pu.png"])')
$(tr:animated)處於動畫狀態的tr
$(input:button)包括type類型為button,reset,submit的Input
$(input:checkbox)等同於$(input[type=checkbox])
$(span:contains(food))包含文字food的span
$(input:disabled)禁用
$(input:enabled)啟用
$(input:file)等同於$(input[type=file])
$(:header)h1到h6
$(input:hidden)
$(input:image)等同於$(input[type=image])
$(:input)包括input, select, textarea, button元素
$(tr:parent)
$(input:password)等同於$(input[type=password])
$(input:radio)等同於$(input[type=radio])
$(input:reset)等同於$(input[type=reset])或$(button[type=reset])
$('.clssname:selected')
$(input:submit)等同於$(input[type=submit])或$(button[type=submit])
$(input:text)等同於$(input[type=text])
$(div:visible)

3、處理DOM元素  

操作元素的屬性:

$('*').each(function(n){ this.id = this.tagName + n;})

擷取屬性值:

$('').attr('');

設定屬性值:

$('*').attr('title', function(index, previousValue){ return previousValue + ' I am element ' + index + ' and my name is ' + this.id;}) //為一個屬性設定值$('input').attr({ value: '', title: ''}); //為多個屬性設定值

刪除屬性:

$('p').removeAttr('value');

讓所有連結都在新視窗中開啟:

$('a[href^="http://"]').attr('target',"_blank");

避免表單多次提交:

$("form").submit(function(){ $(":submit", this).attr("disabled","disabled");})

添加類名:

$('#id').addClass('')

刪除類名:

$('#id').removeClass('')

切換類名:

$('#id').toggleClass('')

存在就刪除類名,不存在就添加類名
判斷是否含有類名:

$('p:first').hasClass('') $('p:first').is('')

以數組形式返回類名列表:

$.fn.getClassNames = function(){ var name = this.attr('someclsssname'); if(name != null){ return name.split(" "); } else { return []; }}

設定樣式:

$('div.someclassname').css(function(index, currentWidth){ return currentWidth + 20;});$('div').css({ cursor: 'pointer', border: '1px solid black', padding: '12px 12px 20px 20x', bacgroundColor: 'White'});

有關尺寸:

$(div).width(500)
$('div').height()
$('div').innerHeight()
$('div').innerWidth()
$('div').outerHeight(true)
$('div').outerWidth(false)

有關定位:

$('p').offset()相對於文檔的參照位置
$('p').position()位移父元素的相對位置
$('p').scrollLeft()水平捲軸的位移值
$('p').scrollLeft(value)
$('p').scrollTop()
$('p').scrollTop(value)

有關元素內容:

$('p').html()
$('p').html('')
$('p').text()
$('p').text('')

追加內容

在元素末尾追加一段html:

$('p').append('<b>some text</b>');

在元素末尾dom中現有的元素:

$('p').append($(a.someclassname))

在元素開頭追加:

$("p").prepend()

在元素的前面追加:

$("span").before()

在元素的後面追加:

$("span")after()

把內容追加到末尾:

appendTo(targets)

把內容追加到開頭:

prependTo(targets)

把內容追加到元素前面:

insertBefore(targets)

把內容追加到元素後面:

$('<p></p>').insertAfter('p img');

包裹元素:

$('a.someclassname').wrap("<div class='hello'></div>")
$('a.someclassname').wrap($("div:first")[0])
$('a.someclassname').wrapAll()
$('a.someclassname').wrapInner()
$('a.someclassname').unWrap()

刪除元素:

$('.classname').remove()刪除元素,綁定到元素上的事件和資料也會被刪除
$('.classname').detach()刪除元素,但保留事件和資料
$('.classname').empty()不刪除元素,但清空元素內容

複製元素:

$('img').clone().appendTo('p.someclassname')
$('ul').clone().insertBefore('#id')

替換元素:

$('img[alt]').each(function(){ $(this).replaceWith('<span>' + $(this).attr('alt') + '</span>');})$("p").replaceAll("<b></b>")

關於表單元素的值:

$('[name="radioGroup"]:checked').val()擷取選項按鈕的值,如果沒有選中一個,返回undefinedvar checkboxValues = $('[name="checkboxGroup"]:checked').map(function(){ return $(this).val();}).toArray(); //擷取多選框的值

對於<select id="list" multiple="multiple">使用$('#list').val()傳回值的數組
$('input').val(['one','two','three'])如果單選框或複選框與數組中的元素匹配,則選中狀態

相信本文所述對大家的jQuery程式設計有一定的借鑒價值。


利用jQuery操作HTML元素的方法

jQuery 選取器

jQuery 元素選取器和屬性選取器允許您通過標籤名、屬性名稱或內容對 HTML 元素進行選擇。
選取器允許您對 HTML 元素組或單個元素進行操作。
在 HTML DOM 術語中:
選取器允許您對 DOM 元素組或單個 DOM 節點進行操作。

選取器  執行個體  選取

*  $("*")  所有元素
#id  $("#lastname")  id="lastname" 的元素
.class  $(".intro")  所有 class="intro" 的元素
element  $("p")  所有 <p> 元素
.class.class  $(".intro.demo")  所有 class="intro" 且 class="demo" 的元素
     
:first  $("p:first")  第一個 <p> 元素
:last  $("p:last")  最後一個 <p> 元素
:even  $("tr:even")  所有偶數 <tr> 元素
:odd  $("tr:odd")  所有奇數 <tr> 元素
     
:eq(index)  $("ul li:eq(3)")  列表中的第四個元素(index 從 0 開始)
:gt(no)  $("ul li:gt(3)")  列出 index 大於 3 的元素
:lt(no)  $("ul li:lt(3)")  列出 index 小於 3 的元素
:not(selector)  $("input:not(:empty)")  所有不為空白的 input 元素
     
:header  $(":header")  所有標題元素 <h1> - <h6>
:animated     所有動畫元素
     
:contains(text)  $(":contains('W3School')")  包含指定字串的所有元素
:empty  $(":empty")  無子(元素)節點的所有元素
:hidden  $("p:hidden")  所有隱藏的 <p> 元素
:visible  $("table:visible")  所有可見的表格
     
s1,s2,s3  $("th,td,.intro")  所有帶有匹配選擇的元素
     
[attribute]  $("[href]")  所有帶有 href 屬性的元素
[attribute=value]  $("[href='#']")  所有 href 屬性的值等於 "#" 的元素
[attribute!=value]  $("[href!='#']")  所有 href 屬性的值不等於 "#&quot......餘下全文>>
 
jquery幾種頁面元素定位及操作的方法

jQuery提供兩種方式來選擇html的elements,第一種是用CSS和Xpath選取器聯合起來形成一個字串來傳送到jQuery的構造器(如:$("div > ul a"));第二種是用jQuery對象的幾個methods(方法)。這兩種方式還可以聯合起來混合使用。我們來試著在我們的test.html代碼中選擇並修改第一個ordered list.一開始,我們需要選擇這個list本身,這個list有一個ID叫“orderedlist”,通常的javascript寫法是document.getElementById("orderedlist").在jQuery中,代碼如下:$(document).ready(function() { $("#orderedlist").addClass("red");});若將一個CSS樣式blue附加到了orderedlist上,在你重新整理了test.html後,你將會看到第一個有序列表(ordered list )背景色變成了藍色,而第二個有序列表沒有變化.代碼如下:$(document).ready(function() { $("#orderedlist > li").addClass("blue"); }); 這樣,所有orderedlist中的li都附加了樣式"blue"。如果要實現把滑鼠放在li對象上面和移開時進行樣式切換,但只在list的最後一個element上生效。$(document).ready(function() { $("#orderedlist li:last").hover(function() { $(this).addClass("green"); }, function() { $(this).removeClass("green"); }); }); find() 讓你在已經選擇的element中作條件尋找,因此 $("#orderedlist).find("li") 就像 $("#orderedlist li")一樣。each()方法迭代了所有的li,並可以在此基礎上作更多的處理。 大部分的方法,如addClass(), 都可以用它們自己的 each() 。html()用來擷取每個li的html文本, 追加一些文字,並將之設定為li的html文本。jQuery 提供了filter() 和not() 兩個方法。 filter()以過濾運算式來減少不符合的被選擇項, not()則用來取消所有符合過濾運算式的被選擇項. 考慮一個無序的list,你想要選擇所有的沒有ul子項目的li元素。$(document).ready(function() { $("li").not(":has(ul)").css("border", "1px solid black");//原文為$("li").not("[ul]").css("border", "1px solid black"); }); 這個代碼選擇了所有的li元素,然後去除了有ul子項目的li元素。刷......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.