首頁  >  文章  >  web前端  >  jQuery的基本運作原理

jQuery的基本運作原理

无忌哥哥
无忌哥哥原創
2018-06-29 10:43:462118瀏覽

 一次獲取多個元素,然後循環進行處理,這樣的操作在js中非常普遍,為了簡化這類操作,jQuery橫空出世,

 下面我們用jQuery來快速改寫一下,體驗jQuery帶來了的,前所未有的酸爽感覺

 首先我們要導入一個jQuery,這裡我先用cdn快速導入jquery函數庫,演示一下

2678f09eece942ca9c6ecaee191009cc

582fcad2919483bdecdd8fbd47b48a232cacc6d41bbb37262a98f745aa00fbf0

e8aa17c26bc1a90e178fbc8865c6704f

ad23e7fcbfe581f1b2bd15b5dfef8ebf

$('li:nth-child(4) ~ *').css({'background-color':'orangered','color':'white'} )

2cacc6d41bbb37262a98f745aa00fbf0

//同時處理多個元素,你會發現只有第5個背景發生變化,這是為什麼呢?

//雖然選擇器li:nth-child(4)~*選擇了多個元素,但是querySelector()中會回傳一個,所以只回傳了符合條件的第一個元素

// document.querySelector ('li:nth-child(4) ~ *').style.backgroundColor = 'lightgreen'

//如何才能取得到所有符合選擇器條件的元素呢?需要使用querySelectorAll()方法

//因為傳回的是一個元素集合(陣列),我們需要用迴圈來完成這個運算

var balls = document.querySelectorAll('li:nth-child(4) ~ *')
alert(balls.length)
for (var i=0; i<balls.length; i++) {
balls[i].style.backgroundColor = &#39;lightgreen&#39;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>1.jQuery的基本工作原理</title>
<style type="text/css">
ul {
margin:30px;
padding:10px;
overflow: hidden;
}
li {
list-style-type: none;
width: 40px;
height: 40px;
margin-left:10px;
background-color: lightskyblue;
text-align: center;
line-height: 40px;
font-size: 1.2em;
font-weight: bolder;
float:left;
border-radius: 50%;
box-shadow: 2px 2px 2px #808080;
}
/*将第一个li背景换成绿色*/
li:first-child {
/*background-color: lightgreen;*/
}
/*再将第4个元素背景换成橙色,前景换成白色*/
li:nth-child(4) {
/*background-color: orangered;*/
/*color: white;*/
}
li:nth-child(4) ~ * {
/*background-color: lightgreen;*/
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</body>
</html>


以上是jQuery的基本運作原理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:js的入門知識下一篇:js的入門知識