我正在尝试编写一个用户脚本,该脚本将:
- 在每个超链接后面添加一个复选框
- 然后,在单击复选框后,相应的超链接将更改其状态为“已访问”。 (颜色将从蓝色更改为紫色。)
问题在于,我不知道如何将 a
元素的 href
值“移动”到 desired_element
变量中。
为了使示例相对简单,我使用维基百科。 但是,在现实生活中,它被用于不同的HTML结构,因此可能最好使用jQuery。(可能使用.closest
然后使用 .find
?)
维基百科案例:
<p>In <a href="/wiki/Computer_programming">computer
programming<input type="checkbox"></a>, a naming convention
is...</p>
<!-- https://en.wikipedia.org/wiki/Naming_convention_(programming) -->
真实案例:
<div>
<figure>
<div>
<div>
<img src="image.png">
</div>
<a href="https://example.com/>Click Me</a>
</div>
</div>
<input type="checkbox">
</div>
// ==UserScript==
// @grant none
// @match https://*.wikipedia.org/*
// @name Wikipedia
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
// ==/UserScript==
(function() {
'use strict';
function actionFunction() {
var links = document.querySelectorAll('a');
var i;
for (i = 0; i < links.length; i++) {
var input = document.createElement('input');
input.setAttribute('type', 'checkbox');
//input.addEventListener("change", aaa);
input.onchange = function() {aaa()};
links[i].appendChild(input);
}
}
function aaa() {
var current_url;
// var desired_url = something?.parentNode.href;
// store the current URL
current_url = window.location.href;
// use replaceState to push a new entry into the browser's history
history.replaceState({}, '', desired_url);
// use replaceState again to reset the URL
history.replaceState({}, '', current_url);
}
actionFunction();
})();
var desired_url ='https://...'
)。这个想法来自于这里:https://dev59.com/x3RA5IYBdhLWcg3w4R_o。 - john c. j.