网址是这样的:
http://www.example.com/index.php?main_page=advanced_search_result&keyword=Sons+of+Anarchy
上面的搜索关键字是Sons of Anarchy
。现在,有没有办法在搜索结果页面上的js搜索结果内容中为关键字添加颜色。谢谢。
ps:搜索输入框:<input type="text" class="keybg" id="keyword" name="keyword">
$sData['pfrom'] = (isset($_GET['pfrom']) ? zen_output_string($_GET['pfrom']) : '');
$sData['pto'] = (isset($_GET['pto']) ? zen_output_string($_GET['pto']) : '');
上面的方法是在url中添加一个参数。
http://www.example.com/index.php?main_page=advanced_search_result&keyword=Sons+of+Anarchy&pfrom=...pto=..
答案 0 :(得分:1)
试试这个(假设您正在将jQuery加载到页面中):
myFile.php
==========
<?php
$sData['pfrom'] = (isset($_GET['pfrom'])
? zen_output_string($_GET['pfrom'])
: '');
$sData['pto'] = (isset($_GET['pto'])
? zen_output_string($_GET['pto'])
: '');
// ... your other code here
?>
<!-- PUT THIS SCRIPT AT THE END OF YOUR HTML BODY ELEMENT -->
<script type="text/javascript">
// get the current URL
var url = window.location.toString();
//get the parameters
url.match(/\?(.+)$/);
var params = RegExp.$1;
// split up the query string and store in an
// associative array
var params = params.split("&");
var queryStringList = {};
for (var i=0;i<params.length;i++) {
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
// get the body html and update it to have keyword colored
var searchKeyword = queryStringList.keyword;
var searchRegex = new Regexp('/'+searchKeyword+'/', 'gi');
var html = $('body').html();
var coloredHTML = html
.replace(searchRegex,
"<span style="color:green">"+html+"</span>");
$('body').html(coloredHTML);
</script>
答案 1 :(得分:1)
你可以这样做:
document.body.innerHTML = document.body.innerHTML.replace(/Anarchy/ig, '<mark>Anarchy</mark>');
答案 2 :(得分:0)
我认为你想要的是这样的。
代码:
var searchKey = 'rray($';
highlight(searchKey, $('div'));
searchKey = '|| !';
highlight(searchKey, $('div'));
function highlight(word, $target){
var conts = $target.html().split('<').join('><').split('>');
var escapeRgx = /([\/\.\*\+\?\|\(\)\[\]\{\}\\\:\$\^])/g;
var searchRgx = new RegExp(word.replace(escapeRgx, '\\$1'), 'gi');
$.each(conts, function(idx, str){
if(str.charAt(0) != '<'){
conts[idx] = str.replace(searchRgx, '<span class="mark">' + word + '</span>') ;
} else {
conts[idx] = str + '>';
}
});
$target.html(conts.join(''));
}
要获取搜索关键字,您可以在后端检索它,并将其回显给前端。即,
<? echo 'var searchKey = "'. $_GET['key'] .'"'; ?>
这是演示 - http://jsfiddle.net/jn7TC/4/