Javascript 使用jquery显示搜索中的匹配行
我有一段代码,可以从输入源搜索页面上显示的当前信息,输入源是加载到中的XML。然后显示找到单词的次数,然后显示找到单词的行,尽管当前显示的是所有行。代码是Javascript 使用jquery显示搜索中的匹配行,javascript,jquery,Javascript,Jquery,我有一段代码,可以从输入源搜索页面上显示的当前信息,输入源是加载到中的XML。然后显示找到单词的次数,然后显示找到单词的行,尽管当前显示的是所有行。代码是 function searchResults(query) { var temp = "\\b" + query + "\\b"; var regex_query = new RegExp(temp, "gi"); var currentLine; var num_matching_lines = 0;
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", g_playDOM).each(
function() {
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query,
'<span class="query_match">' + query + '</span>');
if (currentLine.search(regex_query) > 0)
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
});
$("#sideInfo").append(
"<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
$(document).ready(function() {
loadPlay();
$("#term_search").focus(function(event) {
$(this).val("");
});
$("#term_search").keypress(function(event) {
if (event.keyCode == 13)
searchResults($("#term_search").val());
});
$('#term-search-btn').click(function() {
searchResults($("#term_search").val());
});
});
</script>
函数搜索结果(查询){
var temp=“\\b”+query+“\\b”;
var regex_query=new RegExp(temp,“gi”);
无功电流线;
var num_匹配_行=0;
$(“#主输出”).empty();
$(“行”,g_playDOM)。每个(
函数(){
currentLine=$(this.text();
matchesLine=currentLine.replace(regex\u查询,
''+查询+'';
if(currentLine.search(regex_查询)>0)
匹配行数++;
$(“#main output”)。追加(“”+matchesLine+””);
});
$(“#sideInfo”)。追加(
“在“+num\u matching\u line+”行中找到“+query+””;
}
$(文档).ready(函数(){
loadPlay();
$(“#术语搜索”)。焦点(函数(事件){
$(此).val(“”);
});
$(“#术语搜索”)。按键(功能(事件){
如果(event.keyCode==13)
搜索结果($(“#术语搜索”).val();
});
$(“#术语搜索btn”)。单击(函数(){
搜索结果($(“#术语搜索”).val();
});
});
当前,单词所在的行数显示正确 如果希望在条件中执行一行代码,则需要在其周围放置大括号。否则,将只执行下一个操作项。在您的情况下,增加匹配行数的计数 在每个分支上执行后续操作项,将找到的行追加到DOM中,因为
if
语句已经完成了它的工作。下面有冒犯性的字眼:
if ( currentLine.search(regex_query) > 0 ) num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
if(currentLine.search(regex_query)>0)num_matching_line++;
$(“#main output”)。追加(“”+matchesLine+””);
固定的:
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
}
if(currentLine.search(regex\u查询)>0){
匹配行数++;
$(“#main output”)。追加(“”+matchesLine+””);
}
我对此进行了更改,但它仍然显示所有行而不是“匹配行”。你知道为什么会发生这种情况,或者我可以做些什么来解决这个问题吗?你应该使用浏览器的开发工具来突破,并找出哪些文本正在通过。因为您还没有上传一个JSFIDLE.net来显示问题,所以我不能为您这样做。但它可能与replace()
返回的内容有关,即您正在添加matchesLine
而不是currentline
,或者需要查找.val()
而不是.text()
,但很难说,因为您还没有显示HTML。