常用jQuery用法解說

1.所有段落中加入class屬性:
$(function() {
$('p').each(function(index) {
var a= $(this).attr('class');
$(this).attr('class', a+ ' inhabitants');
});
});


2.針對div元素中的chapter class元素,內href屬性內含有wikipedia的所有鏈結標籤(A),做什麼動作?
  • 均加上屬性rel、id、title。
  • id透過.each()依序累計。
  • $(this)等於$thisLink變數,減少$()使用次數可增加效能。


$(function() {
$('div.chapter a[@href*=wikipedia]').each(function(index) {
var $thisLink = $(this);
$(this).attr({
'rel': 'external',
'id': 'wikilink-' + index,
'title': 'learn more about ' + $thisLink.text() + ' at Wikipedia'
});
});
});

3.文章的<p>最後面增加" BACK-TO-TOP LINKS"超連結

$(function() {
$('').prependTo('body');
$('back to top').insertAfter('div.chapter p:gt(2)');
});


4. 若要複製文章中的某一段,可用clone()。
$('div.chapter p:eq(2)').clone(); //不只複製該元素,連後代的元素都會複製。
得到 <p class="article">今天是好天氣</p>

$('div.chapter p:eq(2)').clone(flase); //只複製該元素標籤。
得到 <p class="article"></p>

5.DOM操作方法歸納
  • .append() //元素中插入新元素
  • .appentTo()
  • .prepend()
  • .prependTo()
  • .after() //元素相鄰位置插入新元素
  • .insertAfter()
  • .before()
  • .insertBefore()
  • .wrap() //元素外套上新元素
  • .html() //用新元素或文字替換每個元素
  • .text()
  • .empty() //移除每個符合的元素
  • .remove() //移除但不刪除元素及其後代

沒有留言:

張貼留言