开发者

jQuery: Cannot change style of element after selected

Here is my code. Where you see "alert([...]);", an alert pops up. Why doesn't the CSS style change? The 'click' event doesn't fire either!

resolveSideMenuAddress: function () {
    var firstLink = $("#masterHeaderMenu .masterHeaderMenuButton a:fi开发者_运维百科rst");

    function select(link) {
        alert('i alert');
        link.css({
            'color': '#9a4d9e',
            'cursor': 'default'
        });
        alert('color and cursor not changed');
        link.click(function () {
            alert('click');
            return false;
        });
    }

    if (window.location.pathname === firstLink.attr('href')) {
        alert('i alert');
        select(firstLink);
    }
}

I've tried addClass() and can't change the color of the link that way either.


First, you're not actually firing the click event, but rather applying a click handler to the link. It won't fire until you actually click the link. If you want existing click handlers to be run you can try link.click() (without the function). If you want the link to actually be taken, you should simply set the location to the value of the link's href attribute. Second, I'm not sure why the CSS isn't being applied properly. It looks ok to me. I'd suggest using Firefox/Firebug and inspecting the element after the function has run to see what styles are actually in use.


try using $(link) instead of just link like this:

resolveSideMenuAddress: function () {
    var firstLink = $("#masterHeaderMenu .masterHeaderMenuButton a:first");

    function select(link) {
        alert('i alert');
        $(link).css({
            'color': '#9a4d9e',
            'cursor': 'default'
        });
        alert('color and cursor not changed');
        $(link).click(function () {
            alert('click');
            return false;
        });
    }

    if (window.location.pathname === firstLink.attr('href')) {
        alert('i alert');
        select(firstLink);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜