[英]Setting a custom filter that will exclude the list item titles from the search criteria
這段代碼(我從一本書中拿來的)將過濾器應用於僅搜索正文副本的列表視圖,從搜索條件中排除列表項標題
<body>
<div data-role=”page” id=”MY-page”>
<div data-role=”header”>
<h1>Sports</h1>
</div>
<div data-role=”content”>
<ul data-role=”listview” data-filter=”true”>
<li>Football</li>
<li>Basketball</li>
<li>Tennis</li>
<li>Volleyball</li>
</ul>
<!-- etc. -->
</body>
$(document).bind("mobileinit", function() {
$.mobile.listview.prototype.options.filterCallback = onlyBody;
});
function onlyBody(text, searchValue) {
var splitText = text.trim().split("\n");
console.log(" text: "+ splitText[1]);
return splitText[1].toLowerCase().indexOf( searchValue ) === -1;
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,””);
}
我沒看懂這段代碼
return splitText[1].toLowerCase().indexOf( searchValue ) === -1;
我知道indexOf
返回一個數字,表示指定searchvalue
第一次出現的位置,或者-1
如果它從未出現並且===
運算符返回一個布爾值。 為什么我們要返回一個布爾值?
此外,我沒有注意到在關閉 body 標記之前將此代碼放入腳本標記后,jQuery Mobile 中的默認過濾器發生了變化。 如何確保此代碼正常工作?
將其分解為每個步驟:
splitText[1]
返回splitText
數組的第二個元素(因為數組索引從零開始)
.toLowerCase()
數組的值是一個字符串,這會將值轉換為完全小寫。
.indexOf(searchValue) === -1;
indexOf()
在調用它的字符串/數組中查找給定值,並將其在字符串中的位置作為整數返回。 這個整數是匹配的起始索引。 如果未找到匹配項,則返回-1
。
return splitText[1].toLowerCase().indexOf(searchValue) === -1;
把他們放在一起回來,這行代碼將返回true
如果searchValue
不在的第二個項目中發現splitText
陣列。
不幸的是,您沒有向我們展示足夠的代碼來了解為什么返回這個布爾值,或者它是如何使用的。 為此,您需要檢查 listView 中的邏輯以查看$.mobile.listview.prototype.options.filterCallback
值是如何使用的。
我找到了我的問題的答案:為什么我們要返回一個布爾值?
要設置將成為所有可過濾小部件的新默認值的自定義過濾功能,請在“mobileinit”信號處理程序中覆蓋可過濾小部件原型中的 filterCallback 選項:
$( document ).one( "mobileinit", function() {
$.mobile.filterable.prototype.options.filterCallback = function( index, searchValue ) {
// In this function the keyword "this" refers to the element for which the
// code must decide whether it is to be filtered or not.
// A return value of true indicates that the element referred to by the
// keyword "this" is to be filtered.
// Returning false indicates that the item is to be displayed.
//
// your custom filtering logic goes here
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.