each()
.each() ,同JS的迴圈
<p>Hello I am paragraph number 1</p>
<p>Hello I am paragraph number 2</p>
<p>Hello I am paragraph number 3</p>
<p>Hello I am paragraph number 4</p>欲印出
Hello I am paragraph number 1
Hello I am paragraph number 2
Hello I am paragraph number 3
Hello I am paragraph number 4_____//element 當前的DOM元素,也可使用this選擇器代替(element = this)寫法1: console內使用JS語法,利用.innerHTML印出$(document).ready(function () {
$(‘p’).each(function(index, element){
console.log(element.innerHTML)
})寫法2:console內使用jQ語法,使用jQ選擇器$(document).ready(function () {
$(‘p’).each(function(index, element){
console.log($(element).text())
})寫法3:console內使用jQ語法,使用this代替element,並運用變數手法$(document).ready(function () {
$(‘p’).each(function(index, element){
let item = $(this)
console.log(item.text())
})
上面是使用匿名函式的方式,也可寫成這樣:
$(document).ready(function () {
$(‘p’).each(iteration)
function iteration(){
let item = $(this)
console.log(item.text())}
})
例子:印出每個class name
<p class=”one”>Hello I am paragraph number 1</p>
<p class=”two”>Hello I am paragraph number 2</p>
<p class=”three”>Hello I am paragraph number 3</p>
<p class=”four”>Hello I am paragraph number 4</p>
<p>I am simple paragraph</p>
_____ let classNames = []; $(‘p[class]’).each(function(i){ //選取每個有class的p進行迴圈
classNames[i]=$(this).attr(‘class’)})
// 印出每個p的class屬性(也就是one, two, three, four) console.log(classNames.join(‘,’)) //將陣列轉為以, 分隔的字串
例子:利用迴圈搭配條件,選取奇數與偶數項與不同背景色
<ul>
<li>Odd list item</li>
<li>Even list item</li>
<li>Odd list item</li>
<li>Even list item</li>
<li>Odd list item</li>
</ul>_____$(document).ready(function () {
$(‘li’).each(function(index){
if(index%2==1){
$(this).css(‘background-color’,’greenyellow’)
}else{ $(this).css(‘background-color’, ‘pink’)}})
})
利用attribute finction陣列的方式,為img加入多種屬性
<img>
<img>
<img>
<img>
<img>
_____$(document).ready(function(){
$(‘img’).each(function(index){
if(index%2===1){
$(this).attr(
{ src:‘img-1.jpg',
title:’shinamonn’,
style:’height:100px’,
class:’odd’})}else if(index % 2 === 0){
$(this).attr(
{ src:‘img-2.jphg',
title: ‘kitty’,
style: ‘height:100px’,
class: ‘even’})}})})