我有一个带有Ui Li结构的树视图列表,我想创建一个基于jquery的搜索,它将选择或突出显示树中的文本。
可以帮助吗?
以下是树视图示例:
<ul>
<li menuid="1">
<span class="arrow collapsible expand"> </span>
<span><a href="#" name="basenode">ML034</a></span>
<ul>
<li menuid="338">
<span class="arrow collapsible expand"> </span>
<span><a href="#" name="basenode">DRUM RACK</a></span>
<ul>
<li menuid="339"><span class="arrow"> </span>
<span><a href="#" name="basenode">000000001615</a></span>
</li>
</ul>
</li>
</ul>
答案 0 :(得分:1)
<input type="text" id="search" />
<style>
.highlight {
background: red;
}
</style>
<script>
$(function(){
$('#search').on('keyup', function (){
var val = $(this).val().toLowerCase()
if (val) {
$('ul li span a').each(function(idx, obj){
if ($(obj).text().toLowerCase().indexOf(val) !== -1)
$(obj).addClass('highlight')
else
$(obj).removeClass('highlight')
})
}
else
$('ul li span a').removeClass('highlight')
})
})
</script>
答案 1 :(得分:0)
试试这个:
var searchTree: function (textInput) {
var count=0;
if (textInput === '') {
this.find('li:visible').removeClass('search-item-tree');
}
else {
count = this.find('li:visible').removeClass('search-item-tree').filter(function () {
var v = $(this).data();
if (v.name.toUpperCase().indexOf(textInput.toUpperCase().trim()) !== -1) {
$(this).find('[name="basenode"]:first').addClass('search-item-tree');
return true;
}
return false;
}).length;
}
return count;
}
风格:
.search-item-tree{
font-style: italic;
font-weight: bold;
background-color:lightgreen;
}
例如:事件更改输入搜索
searchTree.call($('tree selector'),$(this).val())
答案 2 :(得分:0)
使用jQuery在这篇stackoverflow帖子中找到了一个很好的答案。
根据此处发布的解决方案,您的问题answer。
(function (elem, fun) {
$(elem)
.find(":not(iframe)")
.addBack()
.contents()
.filter(function () {
return this.nodeType === 3 && skipSpace(this.nodeValue) && fun(this.parentNode);
});
})("ul:first", function(node) { node.style.color = "red"; });
function skipSpace(str) {
var index = str.search(/^[\S]/);
if (index === -1) {
return "";
}
return str.slice(index);
}
它突出显示所有不是空格的文本元素。
我只使用javascript:
来提出这个solution(function searchAndApply(node, fun) {
if(!node) {
return;
}
searchAndApply(node.nextSibling, fun);
searchAndApply(node.firstChild, fun);
if(node.nodeType === 3) {
return skipSpace(node.nodeValue) && fun(node.parentNode);
}
})(document.querySelector("ul:first-child"), function (node) {
node.style.color = "red";
});
function skipSpace(str) {
var index = str.search(/^[\S]/);
if (index === -1) {
return "";
}
return str.slice(index);
}
它完全一样。
亲切的问候。