使用jQuery使用其中一个元素拥有CSS属性来设置元素的CSS?

时间:2011-04-12 02:34:52

标签: jquery

我正在尝试为我的webapps中的所有javascript脚本超链接添加标准样式。用虚线替换标准实线。这可以通过CSS实现,但是存在一个主要缺点,边框颜色与链接颜色不匹配。我想,因为链接正在使用JS,为什么不用JS做。这是我在jQuery中尝试做的事情。

$(function(){
    $('a.scripted').css({
        'text-decoration': 'none',
        'border-bottom': '1px dotted',
        'border-color': $(this).css('color'),
    });
});

然而,这不起作用。 $(this)不引用所选元素,这是有道理的。我的问题是,我该怎么做?我试着像这样包装它:

$(function(){
    $('a.scripted').ready(function(){
        $(this).css({
        'text-decoration': 'none',
        'border-bottom': '1px dotted',
        'border-color': $(this).css('color'),
        });
    });
});

这也行不通。建议?

修改

此代码可用,但不适用于访问过的链接。我知道jQuery选择器:visited,但我如何在此上下文中使用它?

$(function(){
    $('a.scripted').each(function(){

        var $this = $(this);

        $this.css({
            'text-decoration': 'none',
            'border-bottom': '2px dotted',
            'border-color': $this.css('color'),
        });

        $this.hover(
            function()
            {
                $this.css({
                    'text-decoration': 'none',
                    'border-bottom': '1px dotted',
                    'border-color': $this.css('color'),
                });
            },
            function()
            {
                $this.css({
                    'text-decoration': 'none',
                    'border-bottom': '1px dotted',
                    'border-color': $this.css('color'),
                });
            }
        );

        $this.click(function(){
            $this.css({
                'text-decoration': 'none',
                'border-bottom': '1px dotted',
                'border-color': $this.css('color'),
            });
        });
    });
});

4 个答案:

答案 0 :(得分:2)

你可以使用each,然后使用$(this)来为你提供对迭代元素的引用。

$(function(){
    $('a.scripted').each( function() {
        var $this = $(this);
        $this.css({
           'text-decoration': 'none',
           'border-bottom': '1px dotted',
           'border-color': $this.css('color')
        });
    });
});

答案 1 :(得分:1)

我会使用每种方法。

$('a.scripted').each(function () {
    $(this).css({
        'text-decoration': 'none',
        'border-bottom': '1px dotted',
        'border-color': $(this).css('color'),
    });
});

答案 2 :(得分:0)

$(function(){
    $('a.scripted').css({
        'text-decoration': 'none',
        'border-bottom': '1px dotted ',
    });
});

检查http://jsfiddle.net/qERuL/5/

处的工作示例

答案 3 :(得分:-1)

如果可能的话,你真的应该用css来做。无论您在何处设置链接颜色,还可以设置脚本链接的底部颜色。如果您有多个可以显示这些链接的地方(每个地方都有不同的颜色),请为每个地点写一个a.scripted块。

a {
  color: blue; /* or whatever color you like */
}
a.scripted {
  text-decoration: none;
  border-bottom: 1px dotted;
  border-color: blue; /* same as above */
}