我傾向于撰寫自己的用戶腳本(又名Violentmonkey / Tampermonkey腳本;以前的 Greasemonkey 腳本)。在這樣做時,我經常最終按類名選擇元素 - 使用本機 javascript 或讓腳本加載 jQuery 并使用它。
我注意到,像“SeriesIndexFooter-footer-有時我看到動態生成的類名3WmRg ”用粗體位看似是一些隨機生成的部分(我認為出這種被產生的?我還沒有使用自己做出反應,但有時有遇到這些時在其他元素名稱中看到“React”)。顯然,我可以在我的腳本中硬編碼這些類名,它會作業......但我擔心的是,如果站點/本地服務器應用程式稍后更新,這將破壞我的用戶腳本。
例如
// @run-at document-end
var footer = document.querySelectorAll('.SeriesIndexFooter-footer-3WmRg');
//OR
// @run-at document-end
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js
var footer = jQuery('.SeriesIndexFooter-footer-3WmRg');
有沒有更好的解決方案,它不依賴于硬編碼或完全避免類名,但也降低了我的腳本因為類名的隨機部分更改而中斷的風險?
uj5u.com熱心網友回復:
您無法預測您正在談論的類后綴。
這用于封裝樣式,以便它僅適用于該特定元素或元素組。
在您的情況下,您可以做的是使用少數 CSS 選擇器來中繼搜索屬性中的值。在您的情況下,它看起來像這樣:
document.querySelectorAll('[class*=SeriesIndexFooter-footer]')
如果您需要更具體,您可以鏈接選擇器。例如,您可以定位一種元素div。鏈接選擇器沒有限制,可以更精確地選擇您需要的內容。
document.querySelectorAll('div[class*=SeriesIndexFooter-footer]')
使用此行,您將選擇class屬性具有子字串"SeriesIndexFooter-footer"且為 的所有元素div。
這是 W3Schools 檔案
您可以在此處的 W3Schools 檔案中找到更多適合您的案例的選擇器
您可以使用的其他詞搜索 CSS 選擇器是:
[attribute=value] [target=_blank] Selects all elements with target="_blank"
[attribute~=value] [title~=flower] Selects all elements with a title attribute containing the word "flower"
[attribute|=value] [lang|=en] Selects all elements with a lang attribute value equal to "en" or starting with "en-"
[attribute^=value] a[href^="https"] Selects every <a> element whose href attribute value begins with "https"
[attribute$=value] a[href$=".pdf"] Selects every <a> element whose href attribute value ends with ".pdf"
[attribute*=value] a[href*="w3schools"] Selects every <a> element whose href attribute value contains the substring "w3schools"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/407205.html
標籤:
