获取相对位置的元素的href

问题描述 投票:0回答:1

我正在尝试写一个将要的用户脚本

  1. 在每个超链接后添加一个复选框
  2. 然后,单击复选框后,相应的超链接将其状态更改为“已访问”。 (颜色将从蓝色更改为紫色。)

问题是我不知道如何将href值从a元素“移动”到desired_element变量。

为了使示例相对简单,我使用了Wikipedia。但是,在现实生活中,它打算用于不同的HTML结构,因此使用jQuery可能是一个好主意。

维基百科案例:

<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();
})();
javascript jquery tampermonkey userscripts
1个回答
1
投票

要进行这项工作,您需要在aaa()函数中获得对该元素的引用。为此,您可以将其作为参数传递,也可以在事件处理程序中使用addEventListener并使用this来引用引发事件的元素。后者将是更好的做法。

但是值得注意的是,您无法在a元素内使用复选框,因为您无法嵌套可点击的元素。输入必须是a的同级,可以通过附加到父级来实现。您也可以将URL作为数据属性存储在input中,而不必遍历DOM来查找相关的a。试试这个:

function actionFunction() {
  var links = document.querySelectorAll('a');
  var i;
  for (i = 0; i < links.length; i++) {
    var input = document.createElement('input');
    input.type = 'checkbox';
    input.dataset.url = links[i].href;
    input.addEventListener("change", aaa);
    links[i].parentElement.appendChild(input);
  }
}

function aaa() {
  let desired_url = this.dataset.url;
  let current_url = window.location.href;
  history.replaceState({}, '', desired_url);
  history.replaceState({}, '', current_url);
}

actionFunction();
© www.soinside.com 2019 - 2024. All rights reserved.