设置自定义过滤器,从搜索条件中排除列表项标题

时间:2016-07-10 15:14:43

标签: javascript jquery jquery-mobile filter

此代码(我从一本书中获取)将对listview应用过滤器,该列表视图仅搜索正文副本,但不包括搜索条件中的列表项标题

<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中的默认过滤器已更改。如何确保此代码正常工作?

2 个答案:

答案 0 :(得分:1)

分解为每一步:

splitText[1]

返回splitText数组的第二个元素(因为数组索引从零开始)

.toLowerCase()

数组的值是一个字符串,这会将该值转换为完全小写。

.indexOf(searchValue) === -1;

indexOf()在调用它的字符串/数组中查找给定值,并将其在字符串中的位置作为整数返回。此整数是匹配的起始索引。如果未找到匹配项,则返回-1

return splitText[1].toLowerCase().indexOf(searchValue) === -1;

如果在true数组的第二项中找到searchValue not ,则这一行代码将重新组合在一起splitText

不幸的是,您没有向我们展示足够的代码来了解为什么返回此布尔值,或者如何使用它。为此,您需要检查listView中的逻辑,以查看$.mobile.listview.prototype.options.filterCallback值的使用方式。

答案 1 :(得分:0)

我找到了一个问题的答案:为什么我们要返回一个布尔值?

要设置将成为所有可过滤小部件的新默认值的自定义过滤功能,请在&#34; mobileinit&#34;中覆盖可过滤小部件原型中的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
    });
});

source

相关问题