From 72ab43b411183b229c576f812b630edd8b285188 Mon Sep 17 00:00:00 2001
From: mayx
Date: Mon, 28 Apr 2025 15:40:47 +0000
Subject: Update 2 files
- /assets/js/main.js
- /_posts/2025-04-04-search.md---
_posts/2025-04-04-search.md | 18 ++++++++++++++----
assets/js/main.js | 11 ++++++++++-
2 files changed, 24 insertions(+), 5 deletions(-)
diff --git a/_posts/2025-04-04-search.md b/_posts/2025-04-04-search.md
index 913564a..9283022 100644
--- a/_posts/2025-04-04-search.md
+++ b/_posts/2025-04-04-search.md
@@ -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 => ({
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": '''
+ }[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, '$1');
@@ -51,11 +60,12 @@ $(function() {
});
}
- $('section').each(function() {
+ $('section').each(function () {
highlightTextNodes(this);
});
});
```
+ (2025.04.28更新:解决了一个潜在的解析问题)
我测试了一下,非常符合我的需求,各种情况都能按照我的预期工作,虽然说功能非常简单,但是能正常运行,AI写的还是挺不错的。
# 近期的其他修改
diff --git a/assets/js/main.js b/assets/js/main.js
index 889c1f0..644e2b6 100644
--- a/assets/js/main.js
+++ b/assets/js/main.js
@@ -56,11 +56,20 @@ $(function () {
const regex = new RegExp(`(${escapedKeyword})`, 'gi');
// 递归遍历并高亮文本节点
+ const escapeHTML = str => str.replace(/[&<>"']/g,
+ tag => ({
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": '''
+ }[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, '$1');
--
cgit 1.4.1-2-gfad0