在不使用preventDefault()的情况下单击时更改链接颜色

Change link color onclick without preventDefault()

本文关键字:单击 颜色 链接 情况下 preventDefault      更新时间:2023-09-26

如果单击,我需要更改链接的颜色。

如果我使用event.preventDefault();颜色被永久应用,但链接不起作用,那么uri不会被传递,然后我不能使用$_GET['route'],因为我使用mod_rewrite将所有uri重定向到此$_GET变体^(.*)$ index.php?route=$1

如果我不使用event.preventDefault,链接可以工作,部分也会更改,但addClass只在我单击时应用,然后dissapears。。。

我如何做到这两种行为?是否能够传递URI(HREF),并永久更改颜色onClick

html:

<a href="./section">Section</a>

css:

.active { color: #f00; }

Jquery:

$('a').on('click', function(event) {
    //event.preventDefault
    $(this).addClass("active");
});

您可以在doc ready中尝试此操作,无需指定任何.click()事件:

试试小提琴:http://jsfiddle.net/cmwt8/

$(function(){
    var url = window.location.href; // url should be this way 'http://aaa.com/page/section'
    var link = url.substr(url.lastIndexOf('/') + 1); // then you get here 'section'
    $('[href*="' + link + '"]').addClass("active"); // if found add the class
});

您不需要执行任何JavaScripting。您只需要以下CSS

a:visited { color: #f00; }

编辑。如果您只想突出显示特定的链接,请在<a>链接中添加一个类,即

HTML

<a class="sticky" href="./section">Section</a>

CSS

a.sticky:visited  { color: #f00; }

这样,只有你想保持粘性的超链接才会应用的颜色

你不能这样做,因为在你被重定向到一个页面之后。所有对象类都将重置。

但是你可以把这个放在你的$(document).ready()

var page = window.location.pathname.split('/').pop();
$('a[href$="' + page + '"]').addClass('active');

现在,它所做的是作为页面加载示例,您有

<a href="hello.php">test</a>

作为页面加载。page将获得您的最后一个url,例如www.mysite.com/hello.php并且会找到一个CCD_ 13将匹配的url并添加某个类。

你不能这样做,因为这是点击的自然行为。

如果你使用preventDefault(),这意味着你在强迫自然行为按照你的规则工作。

不管怎样,你仍然可以有一些选择。

  1. $('a').on('click', function(event)
    {
        var href = $(this).attr('href');
        event.preventDefault
        $(this).addClass("active");
        window.location = href;
    });

现在,在这一点上,你的重定向将发挥作用,所以你没有办法知道链接颜色是否已经在上一次点击调用中更改,所以session可以帮助你。

click event内部进行ajax调用,并在页面重定向检查已经设置了during ajax call的会话后立即设置session variable,然后在session已经存在的情况下添加类。

尝试使用

    $('#elementID').on('click', function(event) {
        event.preventDefault();
        $(this).addClass("active");
        window.location.href="./section";
    });

并将锚标记的href更新为"#"。即

<a href="#"