###### tags:`Jquery` Jquery操縱網頁元素 ======= ## $(this).parent() 操縱父元素 - 範例使用購物車點擊變色來當範例 >html ```htmlembedded= <li> <input type="button" class="addCart" value="加入購物車"> 捷安特腳踏車 </li> ``` >jq ```javascript= $(this).parent().toggleClass('active'); ``` ## sibblings 操縱兄弟元素 - 本範例是用每個表單僅允許同時只有一個元素可以發亮 ```javascript= $(document).ready(function() { $('.menu li').click(function(event) { /* Act on the event */ // $(this).addClass('active'); $(this).addClass('active').siblings().removeClass('active'); }); }); ``` ## find() 操縱子元素 - 向下找尋所有含有h3標籤的子元素 ```javascript= $('.cart li').click(function(event) { $(this).find('h3').toggleClass('active'); }); ``` ## QA表單(下滑選單) 以上三種進階實作 ![](https://i.imgur.com/bt0jiay.png) ```javascript= $('.question h3').click(function(event) { // 讓點擊到的 h3 亮起來 $(this).toggleClass('active'); // 讓點擊到的 h3找到父元素 .question ,再找裡面的 P 判斷收闔 $(this).parent().find('p').slideToggle(); // 自己以外的 p 隱藏起來 $(this).parent().siblings().find('p').slideUp(); //自己以外的 h3 移除u樣式 $(this).parent().siblings().find('h3').removeClass('active'); }); ``` ## 動態載入html標籤 - 讓外人看不到原始碼,因為是使用js動態載入 ```javascript= $(document).ready(function(){ //$(".box h1").text('哈哈你看不到'); $('.box').html('<h1>哈哈你看不到我</h1>'); }) ``` ## .on vs .click .on效果一樣 差在會hoising隨時監聽 ```javascript= $('.wrap').on('click','h1',function(event){ event.preventDefault(); alert('有效!'); }); $('.box1').html('<h1>用jQuery動態產生的</h1>'); ``` ## attr() 動態增加HTML標籤屬性 - 可以一次同步改超多html標籤ㄉ屬性 ```javascript= $(document).ready(function() { $('img').attr('width','50'); }); ``` ## remove() 像是移除購物車內商品的功能 >HTML ```htmlmixed= <tr> <td><input type="button" class="remove" value="刪除"></td> <td>內容1</td> </tr> ``` >JQ ```javascript= $(document).ready(function() { $('.remove').click(function(event) { /* Act on the event */ $(this).parent().parent().hide(); }); }); ``` ## scrollTop 滾動效果 - 一般電商網站都使用img圖示表示往上移動 ```javascript= $(document).ready(function() { $('.top a').click(function(event) { event.preventDefault(); $('html,body').animate({ scrollTop: 0 }, 1000); }); ``` ## fontAwesome動態載入icon - #### CDN: <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css'/> - [fontAwesome](https://fontawesome.com/) 可以動態載入別人的套件 - 1. [href$='.doc'] 類似模糊搜尋的概念 - 2. fa fa-file-word-o 此套件指定的格式,此段為在文字錢加上icon ```javascript= $(document).ready(function() { $("a[href$='.doc']").addClass('fa fa-file-word-o'); $("a[href$='.jpg']").addClass('fa fa-file-photo-o'); $("a[href$='.zip']").addClass('fa fa-file-zip-o'); }); ```