[英]How to implement “OR” logic instead of “AND” in jQuery?
我正在嘗試修改插件,以便它可以與組內的“或”邏輯以及組間的“與”邏輯一起使用。 這是工作示例 。 我的代碼如下:
if ($.inArray(tag, itemTags) > -1) {
return true;
}
如果我在tag
有["One","Two"]
,則如何實現OR邏輯。
我已經用我認為的功能更新了您的小提琴 。
我只是稍微改變了邏輯。
如果您要定位的瀏覽器提供array.filter
,則可以這樣進行:
var matchingTags = itemTags.filter(function(el) {
return $.inArray(el, tag) > -1;
});
看到它在行動 。
使用ES5的.some
方法,這可能非常簡潔。 較舊的瀏覽器有一個墊片 。
var tag = ["d", "b"],
tagItems = ["a", "b", "c", "d", "e"];
var contains = tagItems.some(function(v) { // whether at least "d" or "b" is in `tagItems`
return ~tag.indexOf(v);
});
if(contains) {
// ...
此tagItems
行為如下:
tag = ["d", "b"]; // contains === true (due to "d")
tag = ["foo", "x", "a"]; // contains === true (due to "a")
tag = ["bar"]; // contains === false (due to no matches)
您還可以為此創建一個輔助函數:
$.inArrayMultiple = function(subset, arr) {
return arr.some(function(v) {
return ~subset.indexOf(v);
});
};
然后您可以使用:
if($.inArrayMultiple(tag, itemTags)) {
// ...
環形交叉口解決方案是將inArray
條件包裝在$(array).each()
函數中,如果數組中存在任何迭代項,則該函數返回true。
var result = function ()
{
var r = false;
$(tag).each(function()
{
if ($.inArray(this, itemTags) > -1)
{
r = true;
}
});
return r;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.