本文目錄一覽:
- 1、javascript contains怎麼用
- 2、javascript 求一段js contains方法代碼
- 3、js怎麼判斷某個數組裡面是否包含這個元素?
- 4、怎樣使用js contains方法
javascript contains怎麼用
這個函數是jQuery裡面的工具函數吧。
語法:
jQuery.contains(container,contained) //返回值是bool類型。
參數:
container:DOM元素作為容器,可以包含其他元素
contained:DOM節點,可能被其他元素所包含
檢測下試一試:
jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false
javascript 求一段js contains方法代碼
註:下面的代碼僅適用於ie
div id=”d1″ onmouseout=”mouseout()”
function mouseout(){
if(event.srcElement == document.getElementById(“d1”)){
是div的mouse事件,執行操作
}else{
不是div的事件
}
}
a的onmouseover事件肯定會觸發的,只不過你可以在這些事件里作一些判斷
如果是a的事件,就不處理一些東西
還真很少用contains,不過效果是一樣的,改了:
div id=”d1″ onmouseout=”mouseout()” style=”width:100px;height:100px”
a onmouseover=”t1(this);” href=”” alt=”” /
/div
script type=”text/javascript”
function t1(obj){
var root = document.getElementById(“d1”);
if(root.contains(obj)){
alert(“是div的子結點”);
return false;
}else {
alert(“不是div的子結點”);
return true;
}
}
/script
js怎麼判斷某個數組裡面是否包含這個元素?
在C#語法中判斷集合是否包含某個元素可以使用Contains方法,但是類似的問題在javascript中要怎麼處理呢,js中沒有Contains方法。
我們可以利用js的原型擴展來封裝一個我們自己的Contains方法。
script type=”text/javascript”
$(function () {
Array.prototype.contains = function (element) { //利用Array的原型prototype點出一個我想要封裝的方法名contains
for (var i = 0; i this.length; i++) {
if (this[i] == element) { //如果數組中某個元素和你想要測試的元素對象element相等,則證明數組中包含這個元素,返回true
return true;
}
}
}
//用一個例子來驗證一些我們封裝的方法
var $subCategoryID = $(“#hidSubCategory”).val();
var $subCategoryIDs = new Array(); //構造一個數組對象
$subCategoryIDs = $subCategoryID.split(“,”); //為數組賦值
$(“input[type=radio]”).each(function () {
if ($subCategoryIDs.contains($(this).attr(“id”))) { //利用contains方法判斷數組中是否含有$(this).attr(“id”)
$(this).attr(“checked”, true);
}
})
})
/script
怎樣使用js contains方法
這是字符串的方法吧vara=”hello”console.info(a.contains(“e”));傳入參數這個字符串是否包含此參數如果是則返回true否為false
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/195883.html