gpt4 book ai didi

javascript - 我希望页面在用户单击所有链接后重定向

转载 作者:行者123 更新时间:2023-11-30 09:36:17 25 4
gpt4 key购买 nike

我有这段代码是从旧帖子中获得的,但它似乎不再起作用了,请帮忙。我什至无法再点击链接,但我的主要目标是让用户点击所有链接,然后将页面重定向到我网站上的另一个页面。

<script>
window.onload = function () {
    var anchors, clicked_count, clicked, i, cur_anchor, my_anchor_id;

    anchors = document.getElementsByTagName("a");
    clicked_count = 0;
    clicked = {};

    for (i = 0; i < anchors.length; i++) {
        cur_anchor = anchors[i];
        cur_anchor.setAttribute("link", i);
        cur_anchor.onclick = function (e) {
            e = e || window.event;
            e.preventDefault();

            my_anchor_id = this.getAttribute("link");
            if (!(my_anchor_id in clicked)) {
                clicked[my_anchor_id] = null;
                if (++clicked_count === anchors.length) {
                    console.log("WOULD BE REDIRECTING");
                    //window.location.href = "facebook.com";
                }
            }
        };
    }
};
</script>
<a href="#Link1" id="link">Some Text 1</a>
<a href="#Link2" id="link">Some Text 2</a>
<a href="#Link3" id="link">Some Text 3</a>

最佳答案

首先,修复您的 HTML 您不能拥有多个相同的 id 属性,因为您获得了三次 id="link"。请将其更改为 class="link" 以避免出现问题。

像这样:

<a href="#Link1" class="link">Some Text 1</a>
<a href="#Link2" class="link">Some Text 2</a>
<a href="#Link3" class="link">Some Text 3</a>

如果您使用的是 jQuery,则可以使用更简单的代码实现您所描述的(即单击三个不同链接后重定向)。

下面是一个带注释的示例解决方案,它将检查哪些链接已被点击,并且仅当用户点击所有三个链接时才重定向,无论他以什么顺序点击它们:

    $(document).ready(function() {

// Create an array for clicked elements
var clicked = [];

// Create a click event for every link with class "link"
$('.link').click(function() {

// Check if we didn't clicked that link yet
if (clicked.indexOf($(this).attr('href')) === -1) {

// If we didn't add it's href attribute to "clicked" array"
clicked.push($(this).attr('href'));
}

// If number of clicked links is 3, redirect
if (clicked.length === 3) {
console.log('REDIRECT');
// location.href = 'http://put-your-url-here.com'
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#Link1" class="link">Some Text 1</a>
<a href="#Link2" class="link">Some Text 2</a>
<a href="#Link3" class="link">Some Text 3</a>

关于javascript - 我希望页面在用户单击所有链接后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43407576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com