日常的工作中可能會用到,選取處某個或者某些元素外的所有元素。
這時我們可以使用 jQuery 遍歷中的 not() 方法來排除某些元素,例如根據元素的 #id ,.class 等排除,代碼如下:
$("div.content *").not(".keep");
表示 .content 類的 div 下除 .keep 類以外的所有元素;
另外,注意這里的 * 表示所有元素。
示例:
html
<div class="box"> <span>點擊按鈕刪除下面綠色框中所有不是keep類的元素,keep類的元素用紅色區分。</span> <div class="content"> <input type="checkbox" name="item"><span>蘿卜</span> <input type="checkbox" name="item"><span>青菜</span> <input type="checkbox" name="item" class="keep"><span class="keep">小蔥</span> <input type="checkbox" name="item" class="keep"><span class="keep">豆腐</span> <input type="checkbox" name="item"><span>土豆</span> <input type="checkbox" name="item"><span>茄子</span> <input type="text" value="我也不是keep類的"> </div> <input type="button" value="刪除"> </div>
css
.box{ width:300px; height:200px; padding:10px 20px; } .box>span{ color:#999; } .keep{ color:red; } .content{ width:250px; height:100px; margin:10px 0; border:1px solid green; } input[type='button']{ width:200px; height:35px; margin:10px; border:2px solid #ebbcbe; }
jQuery
$(function(){ $("input:button").click(function() { $("div.content *").not(".keep").each(function() { // "*"表示div.content下的所有元素 $(this).remove(); }); }); })
資源搜索網站大全https://55wd.com 廣州品牌設計公司http://www.maiqicn.com
補充說明:
* 的用法主要有兩種:
1、通配符:代表多有元素。
比如:.container * 表示 .container 下的所以元素。
2、css選擇器內以 * 星號開頭的屬性:
在CSS選擇器內星號 + CSS 屬性,一般區別 IE6 和 IE8 、IE6 和 FF,IE7 和 IE8,IE7 和 FF 瀏覽器之間屬性 CSS HACK。代碼如下:
.cont{
border:1px solid #000; width:220px; *width:300px; }
我們設置了兩個寬度,一個為 220px ,一個帶星號的寬度為 300px。通過各大瀏覽器測試對比,我們會發現在 IE6 和 IE7 中寬度為 300px ,而在 IE8 及以上 MSIE 版本、谷歌瀏覽器、火狐(FF)瀏覽器卻顯示為 220px 寬度。
大家自己可以測試測試看看是否與描述效果相同。
注意:這里屬於星號CSS屬性放置前后位置。