Update 2 files

- /assets/js/main.js
- /_posts/2025-04-04-search.md
This commit is contained in:
mayx 2025-04-28 15:40:47 +00:00
parent 0f00469871
commit 72ab43b411
2 changed files with 24 additions and 5 deletions

View File

@ -20,7 +20,7 @@ tags: [博客, 搜索, 优化]
至于关键词用查询字符串传过去就好了,那我该怎么做呢?我用的搜索脚本叫[Simple-Jekyll-Search](https://github.com/christian-fei/Simple-Jekyll-Search),它的文档其实根本没有写怎么把搜索的请求传到模版里,还好它有个[关于模版的测试脚本](https://github.com/christian-fei/Simple-Jekyll-Search/blob/master/tests/Templater.test.js)里面有写有个query关键词可以把搜索内容给模版渲染出来既然做了这个功能怎么不写在文档里😅不过这个项目已经停止也没法提出什么建议了……
这个功能听起来相当简单我都懒得写了这种简单的功能直接让AI写才对于是我把需求告诉它让它给我实现一份于是这就是让AI给我写的高亮关键词的JS代码经过了一点修改
```javascript
$(function() {
$(function () {
const urlParams = new URLSearchParams(window.location.search);
const keyword = urlParams.get('kw')?.trim();
@ -32,11 +32,20 @@ $(function() {
const regex = new RegExp(`(${escapedKeyword})`, 'gi');
// 递归遍历并高亮文本节点
const escapeHTML = str => str.replace(/[&<>"']/g,
tag => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
}[tag] || tag));
function highlightTextNodes(element) {
$(element).contents().each(function() {
$(element).contents().each(function () {
if (this.nodeType === Node.TEXT_NODE) {
const $this = $(this);
const text = $this.text();
const text = escapeHTML($this.text());
// 使用正则替换并保留原始大小写
if (regex.test(text)) {
const replaced = text.replace(regex, '<mark>$1</mark>');
@ -51,11 +60,12 @@ $(function() {
});
}
$('section').each(function() {
$('section').each(function () {
highlightTextNodes(this);
});
});
```
2025.04.28更新:解决了一个潜在的解析问题)
我测试了一下非常符合我的需求各种情况都能按照我的预期工作虽然说功能非常简单但是能正常运行AI写的还是挺不错的。
# 近期的其他修改

View File

@ -56,11 +56,20 @@ $(function () {
const regex = new RegExp(`(${escapedKeyword})`, 'gi');
// 递归遍历并高亮文本节点
const escapeHTML = str => str.replace(/[&<>"']/g,
tag => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
}[tag] || tag));
function highlightTextNodes(element) {
$(element).contents().each(function () {
if (this.nodeType === Node.TEXT_NODE) {
const $this = $(this);
const text = $this.text();
const text = escapeHTML($this.text());
// 使用正则替换并保留原始大小写
if (regex.test(text)) {
const replaced = text.replace(regex, '<mark>$1</mark>');