JQuery的DOM操作

蔚澜發表於2024-09-07

JQuery基礎教程第四版

第五章:DOM操作方法的簡單歸納

使用JQuery的DOM操作實現以下功能

1.建立新元素

2.插入新元素

3.移動元素

4.包裝元素

5.複製元素

相關程式碼

HTML檔案

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="six.css">
<script src="../js/jquery-3.4.1.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//遍歷<div class='chapter'>中的每個連結,並逐個為它們新增屬性
$('div.chapter a[href*="baidu.com"]').attr({
rel:'external',
// title:'learn more at wikipedia',
title:function(){
//在值回撥函式中, this指向每次回撥時正在操作的那個DOM元素。
return 'Learn more about '+$(this).text()+'at Baidu';
},
//值回撥:給引數傳遞一個函式,而不是具體的值
//這個函式會針對匹配的元素集中的每個元素都呼叫一次,
//呼叫後的返回值將作為屬性的值
//index:代表迭代次數
id:function(index,oldValue){
return 'wikilink-'+index;
}
});
//insertAfter在指定元素的外部插入內容,元素外部的前面
$('<a href="#top">back to top</a>').insertAfter('div.chapter p');
//prependTo在指定元素的內部插入內容,元素內部的前面
$('<a id="top"></a>').prependTo('body');
//取得頁面中某個位置上的元素,將它們插入到另一個位置上
// $('span.footnote').insertBefore('#footer')
//把所有腳註都包裝到一個<ol>中
// .wrapAll('<ol id="notes"></ol>')
//把每個腳註都包裝到自己的<li>中
// .wrap('<li></li>');
//包裝元
var $notes=$('<ol id="notes"></ol>').insertBefore('#footer');
$('span.footnote').each(function(index){
// $('<sup>'+(index+1)+'</sup>').insertBefore(this);
// $(this).appendTo($notes).wrap('<li></li>');
//反向插入方法
// $(this).before('<sup>['+(index+1)+']</sup>')
// .appendTo($notes)
// .wrap('<li></li>');
$(this).before([
'<a href="#footnote-',
index+1,
'" id="context-',
index+1,
'" class="context">',
'<sup>',
index+1,
'</sup></a>',
].join(''))
.appendTo($notes)
.append([
'&nbsp;(<a href="#context-',
index+1,
'">context</a>)'
].join(''))
.wrap('<li id="footnote-'+(index+1)+'"></li>');
//複製元素
$('div.chapter p:eq(0)').clone().insertBefore('div.chapter');
});
$('span.pull-quote').each(function(index){
var $parentParagraph=$(this).parent('p');
$parentParagraph.css('position','relative');
var $clonedCopy=$(this).clone();
$clonedCopy
.addClass('pulled')
//find()找到<span class='drop'>元素集合
.find('span.drop')
//.html將內容改為...,會返回匹配元素中的html標記
.html('&hellip;')
//返回內部jQuery棧中之前選中的元素
.end()
//.text()取得內容時,所有的html標籤都將被忽略,
//而所有HTML實體也會被轉換成對應的字元
.text($clonedCopy.text())
.prependTo($parentParagraph);
});
});
</script>
<h1 id="f-title">Lorem, ipsum periam sed ab commodi aliquam ipsum et?</h1>
<div id="f-author">Lorem ipsum dolor sit amet consec</div>
<h2>Lorem ipsum dolor sit, amet consectetur</h2>
<h3>Lorem ipsum dolor sit amet</h3>
<div class="excerpt">an excerpt</div>
<div class="chapter">
<p class="square">
<span class="pull-quote">It is a Law of Nature <span class="drop">with us</span>
that a male child shall have <strong> one more side</strong>than this father
</span>
Lorem ipsum dolor, sit amet consectetur adipisicing elit.<span class="footnote">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</span> Illo cum dignissimos possimus quasi consectetur voluptatem asperiores veritatis eos reprehenderit animi doloremque amet quibusdam, accusamus delectus earum, soluta beatae. Dolor, tempore!
Quia quam ut ipsum laudantium voluptatem itaque natus eum inventore magnam dolorum odio at hic tempora corporis enim blanditiis facere saepe, velit nihil ipsam. Obcaecati, nobis. Sapiente odit expedita ad.
Magnam adipisci quidem nam quae, rem perferendis sequi iste, illo nihil sint ad est libero laborum consectetur voluptas dolor fugiat ipsa inventore. Nobis obcaecati in, adipisci ducimus tempore qui placeat.
Officiis, quod?<a href="http://www.baidu.com">feefefefffffffffffffffffffff</a> Consequatur autem quibusdam cum voluptates sit, quam voluptate quis, quod ex labore qui molestiae a sunt? Iste provident placeat ipsum possimus laboriosam quaerat. Laudantium inventore labore nesciunt deserunt?
Eius, vel? Magni eaque sapiente accusantium odio sit quod impedit suscipit, obcaecati ullam error, illo doloremque a totam, corporis pariatur. Modi ducimus esse inventore, aut nemo ex quis maiores corporis.
Dolorem quo dicta minus? Sunt iste asperiores est minima mollitia molestiae iure fugit ipsum libero veniam error esse cupiditate rem modi blanditiis voluptatem natus aut, tenetur nam sint quo hic.
Quaerat sequi ullam architecto l<a href="http://www.baidu.com">fffffffffffffffffffffffffffff</a>audantium. Magni deleniti itaque maiores ratione, molestias doloribus! Sit in quam harum nihil laboriosam enim? Ut cum sit officiis explicabo sapiente blanditiis eveniet atque dicta consequuntur!
Dolorem amet dolor quod atque, nobis aspernatur error totam dicta quisquam vero eos incidunt fuga. Tenetur quisquam quae, qui fugiat magni cum, ipsum vitae repellendus, expedita soluta autem iusto! Quasi.
</p>
<p class="nobility hexagon">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Inventore possimus eaque cum qui labore maxime nostrum ipsa reiciendis, modi voluptatem. Provident quia animi rerum cupiditate placeat delectus exercitationem eius doloremque?
Magnam delectus fugit vero blanditiis porro sint nam aliquam fugiat voluptatibus quod tenetur ab temporibus, asperiores unde placeat provident assumenda dolor quo numquam pariatur, tempora corrupti eum labore ex. Placeat.
Obcaecati, qui incidunt. Libero eius ullam neque, o<a href="http://www.baidu.com">feeeeeeeeeeeeeeeeeeeeeee</a>dio eum cumque voluptatibus quis temporibus quae maiores consectetur expedita laborum cupiditate quod ut natus. Illum eum quo aspernatur culpa tempore veniam sed.
Quidem, laborum cupiditate, <span class="footnote">
Lorem ipsum dolor sit amet consectetur adipisicing
</span>voluptatum quo libero blanditiis dicta praesentium provident eaque consequatur debitis veritatis aperiam hic expedita natus. Architecto consequuntur tempore totam beatae excepturi nulla quidem vitae quia doloribus dolores.
Dolor quisquam nesciunt dolorum debitis voluptas repellat error ab natus corporis iusto illum, quod aperiam sint eius id quam. Vitae eaque fuga, quam minus voluptatum labore nulla ipsam veritatis odit.</p>
<p>
<span class="pull-quote">Lorem ipsum dolor sit amet consectetur<span class="drop"> Lorem ipsum dolor sit amet</span> adipisicing elit. Aliquam, nulla! Itaque mollitia totam animi ut dolorum accusamus, magni quisquam aliquam eveniet cum ipsam optio, aut ipsa. Quasi atque nulla architecto.</span>
consectetur adipisicing elit. P<a href="http://www.baidu.com">uiiiiiiiiityty</a>laceat eveniet nemo esse! Sunt et quam est repellat harum explicabo fugiat, tempore nobis aut repudiandae consequatur veritatis expedita impedit quaerat accusantium?
Inventore natus, non delectus<span class="footnote">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</span> a distinctio at provident odio impedit quo aliquid cum quidem tempore ut quis doloremque error, cumque accusantium quam. Earum blanditiis veritatis commodi adipisci, suscipit ut aliquam!
Corporis nesciunt labore enim, mollitia sunt sit, cum facilis consectetur repellat, necessitatibus vero deleniti ratione beatae facere omnis. Reprehenderit omnis dignissimos laudantium eligendi obcaecati numquam eveniet recusandae. Nisi, obcaecati optio.
</p>
<hr>
<div id="footer"></div>
</div>
</body>
</html>
CSS檔案
.footnote{
font-style: italic;
font-size: 12px;
display: block;
}
.pulled{
display: block;
position: absolute;
width: 120px;
top:-20px;
right: 34px;
padding: 20px;
font:italic 1.2em "Times News Roman",Times,serif;
background: #e5e5e5;
border: 1px solid #999;
border-radius: 8px;
box-shadow: 1px 1px 8px rgba(0,0,0,0.6);
}

實現效果

這些方法幾乎能夠在任何情況下,完成任何任務

(1)要在HTML中建立新元素,使用$()函式

(2)要在每個匹配的元素中插入新元素,使用:

.append();

.appendTo();

.prepend();

.prependTo();

(3)要在每個匹配的元素相鄰位置中插入新元素,使用:

.after();

.insertAfter();

.before();

.insertBefore();

(4)要在每個匹配的元素外部中插入新元素,使用:

.wrap();

.wrapAll();

.wrapInner();

(5)使用新元素或文字替換每個匹配的元素,使用:

.html();

.text();

.replaceAll();

.replaceWith();

(6)移除每個匹配元素中的元素,使用:

.empty()

(7)要從文件中一處每個匹配的元素及後代元素,但不實際刪除它們使用:

.remove()

.detach();

相關文章