[英]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.