【发布时间】:2019-08-02 01:55:29
【问题描述】:
我正在开发 jQuery 快速过滤器 (https://github.com/syropian/jQuery-Quick-Filter),但无法让过滤器使用 span 标题属性进行过滤。
我更改了 github 代码,通过在代码中添加 elem.title 部分,使其也可以按标题属性进行搜索。
这个 sn-p 演示了这个问题:
/*
* Plugin Name: QuickFilter
* Author: Collin Henderson (collin@syropia.net)
* Version: 1.0
* © 2012, http://syropia.net
* You are welcome to freely use and modify this script in your personal and commercial products. Please don't sell it or release it as your own work. Thanks!
* https://github.com/syropian/jQuery-Quick-Filter
* https://stackoverflow.com/questions/42530073/jquery-search-image-title-attribute
*/
(function($) {
$.extend($.expr[':'], {
missing: function(elem, index, match) {
return (elem.textContent || elem.innerText || elem.title || "").toLowerCase().indexOf(match[3]) == -1;
}
});
$.extend($.expr[':'], {
exists: function(elem, i, match, array) {
return (elem.textContent || elem.innerText || elem.title || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
$.extend($.fn, {
quickfilter: function(el) {
return this.each(function() {
var _this = $(this);
var query = _this.val().toLowerCase();
_this.keyup(function() {
query = $(this).val().toLowerCase();
if (query.replace(/\s/g, "") != "") {
$(el + ':exists("' + query.toString() + '")').show();
$(el + ':missing("' + query.toString() + '")').hide();
} else {
$(el).show();
}
});
});
}
});
})(jQuery);
$(document).ready(function() {
$('#txtSearch').quickfilter('#list li');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="txtSearch" placeholder="filter" class="form-control" />
<ul id="list" class="list-group list-group-flush">
<li class="list-group-item" title="banana 1f34c - ????">????</li>
<li class="list-group-item" title="kiwi fruit 1f95d - ????">testing ????</li>
<li class="list-group-item" title="carrots 1f955 - ????"><img src="https://cdn.jsdelivr.net/emojione/assets/svg/1f955.svg" style="width:30px; height:30px"> carrot</li>
<li class="list-group-item" title="bacon 1f953 ????"><img src="https://cdn.jsdelivr.net/emojione/assets/svg/1f953.svg" style="width:30px; height:30px"></li>
<li class="list-group-item" title="cucumber 1f952 ????"><img src="https://cdn.jsdelivr.net/emojione/assets/svg/1f952.svg" style="width:30px; height:30px"> now I can't filter on title attribute but I can search on text between span tags</li>
</ul>
问题是有时我可以过滤 title 属性,但有时我只能过滤 span 标签之间的内容,而不是 span 元素的 title 属性。
- 对于第一项,对于香蕉,我可以粘贴在 ???? emoji 并对其进行过滤,但不会过滤
banana一词,即使它出现在 title 属性中。 - 对于第二个项目,我可以通过
testing或 ???? 搜索。 emoji,但我无法过滤单词kiwi或fruit,即使它们出现在 title 属性中。 - 对于第三项,我可以过滤单词
carrot(在跨度标签之间),但不能过滤出现在标题属性中的单词carrots。 - 对于第四项,我现在可以搜索标题属性,所以可以输入 bacon 并且它可以工作...
-
对于第五项 - 因为现在跨度标签之间有文本,我无法搜索标题属性,但可以搜索跨度标签之间的文本。
我想知道如何让它工作,所以过滤器会检查 title 属性的内容 - 以及 span 标签之间的内容?
【问题讨论】:
标签: javascript jquery html