无服务器 自建短链服务 Url-Shorten-Worker 小改进 | Bootstrap List group | 长链接文本框预搜索localStorage | 代码优化

源码 GitHub: https://github.com/crazypeace/Url-Shorten-Worker

搭建教程: https://zelikk.blogspot.com/2022/07/url-shorten-worker-hide-tutorial.html


效果:



应用 Bootstrap List group 美化

参考:

Bootstrap List group

https://getbootstrap.com/docs/4.0/components/list-group/

JS添加元素时添加class属性

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

实施:

index.html 设置ul 的属性 class list-group

<ul classs="list-group" id="urlList"> 

main.js 设置li 的属性 class list-group-item

let urlList = document.querySelector("#urlList")
let child = document.createElement('li')
let text = document.createTextNode(shortUrl + " " + longUrl)
child.appendChild(text)
child.classList.add("list-group-item")
urlList.append(child)

--------

代码优化

把load.js去掉了,代码并入main.js。向ul列表中添加li的代码提出为函数,在加载页面时和添加短链时调用。

function addUrlToList(shortUrl, longUrl) {
  let urlList = document.querySelector("#urlList")
  let child = document.createElement('li')
  let text = document.createTextNode(shortUrl + " " + longUrl)
  child.appendChild(text)
  child.classList.add("list-group-item")
  urlList.append(child)
}

--------

长链接文本框预搜索localStorage

参考:

文本框内容变化事件

https://www.w3schools.com/jsref/event_oninput.asp

实施:

给长链接的文本框加上oninput事件调用加载loadUrlList()
<input type="text" class="form-control" id="longURL" aria-describedby="basic-addon1" placeholder="Example: https://example.com/" oninput="loadUrlList()">

 loadUrlList() 增加判断长链接文本框内容

// 文本框中的长链接
let longUrl = document.querySelector("#longURL").value
console.log(longUrl)

// 遍历localStorage
let len = localStorage.length
console.log(+len)
for (; len > 0; len--) {
    let keyShortURL = localStorage.key(len - 1)
    let valueLongURL = localStorage.getItem(keyShortURL)
    // 如果长链接为空,加载所有的localStorage
    // 如果长链接不为空,加载匹配的localStorage
    if (longUrl == "" || (longUrl == valueLongURL)) {
      addUrlToList(keyShortURL, valueLongURL)
    }
}

--------

GitHub: https://github.com/crazypeace/Url-Shorten-Worker

评论

The Hot3 in Last 30 Days

无服务器 自建短链服务 Url-Shorten-Worker 完整的部署教程

ClouDNS .asia免费域名 托管到CloudFlare开CDN白嫖Websocket WS通道翻墙 / desec.io