summaryrefslogtreecommitdiff
path: root/_posts
diff options
context:
space:
mode:
authormayx <mayx@outlook.com>2025-04-28 17:40:47 +0200
committermayx <mayx@outlook.com>2025-04-28 17:40:47 +0200
commit72ab43b411183b229c576f812b630edd8b285188 (patch)
tree21cac28bae3673dbd1b258a576286e87ed6b1f49 /_posts
parent0f004698711c4da2f7be0a4b8cc798af89b380da (diff)
Update 2 files
- /assets/js/main.js - /_posts/2025-04-04-search.md
Diffstat (limited to '_posts')
-rw-r--r--_posts/2025-04-04-search.md18
1 files changed, 14 insertions, 4 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 => ({
+ '&': '&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写的还是挺不错的。
# 近期的其他修改