2

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

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

如果我不使用 event.preventDefault 链接有效并且部分更改,但 addClass 仅在我单击时应用,然后消失...

我怎样才能得到这两种行为?能否通过 URI (HREF),并永久更改颜色onClick

html:

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

CSS:

.active { color: #f00; }

查询:

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

5 回答 5

1

你不需要做任何JavaScripting。您只需要以下 CSS

a:visited { color: #f00; }

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

HTML

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

CSS

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

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

于 2013-02-18T05:29:50.360 回答
1

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
});
于 2013-02-18T06:02:09.520 回答
0

尝试使用

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

并将锚标签的href更新为“#”。IE

<a href="#"
于 2013-02-18T05:26:43.737 回答
0

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

但你可以把它放在你的$(document).ready()

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

现在,这就是您拥有的页面加载示例

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

作为页面加载。将page获得您的最后一个网址。www.mysite.com/hello.php 并会找到一个a匹配的 url 并添加特定的类。

于 2013-02-18T05:29:09.170 回答
0

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

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

无论如何,您仍然可以有一些选择。

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

现在此时您的重定向将生效,因此您无法获取链接颜色是否已在之前的点击调用中更改,因此session可以为您提供帮助。

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

于 2013-02-18T05:30:25.397 回答