我如何制作一个按钮来自动单击具有特定rel属性的锚标记?

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

我正在尝试使一个浮在右上角的按钮单击rel属性设置为“ next”的锚标记。标签的代码为:<a href="website" rel="next"><span class="meta-nav screen-reader-text">Next Post</span> Next Chapter</a>

到目前为止,我已经写了这个:

    var button = document.createElement("Button");
    button.innerHTML = "Next";
    button.style = "top:0;right:0;position:fixed;z-index: 9999"
    button.onclick = function(){
        var x = document.querySelector("a");
        for (var i = 0; i < x.length; i++) {
            if(document.x[i].rel = "next"){
               window.location.href = x[i].href;
            }
        }
    }
    document.body.appendChild(button);

但是,当我单击生成的按钮时,它不会单击锚标记。谁能帮忙?

javascript html button anchor
1个回答
1
投票

您想要这样的东西:

var button = document.createElement("Button");
button.innerHTML = "Title";
button.style = "top:0;right:0;position:fixed;z-index: 9999"
button.onclick = function(){
  var x = document.querySelector("a[rel='next']");
  window.location.href = x.href;
}
document.body.appendChild(button);

请参见此jsfiddle:https://jsfiddle.net/nharding/f3m6h74r/18/


1
投票

您可以使用.rel选择器:

.rel
const button = document.createElement("Button");
button.innerHTML = "Title";
button.style = "top:0;right:0;position:fixed;z-index: 9999"
button.onclick = function() {
  const link = document.querySelector("a").rel = "next"
  window.location.href = link.href;
}
document.body.appendChild(button);
© www.soinside.com 2019 - 2024. All rights reserved.