添加类到列表的问题

时间:2014-02-12 06:20:01

标签: jquery

请告诉我为什么我无法在此处添加课程列表:Link 这是代码

$(document).ready(function () {
    // Handler for .ready() called.
    $("li").on("click", function () {
        //alert( $( this ).text() );
        $(this).addClass("red");
    });
});

7 个答案:

答案 0 :(得分:1)

您需要为链接标记添加类而不是li标记。

$(document).ready(function () {
    // Handler for .ready() called.
    $("li a").on("click", function (e) {
        e.preventDefault();
        //alert( $( this ).text() );
        $(this).addClass("red");
    });
});

demo

答案 1 :(得分:0)

正确添加了类,您可能希望将CSS规则更改为:

li.red a {
    color:red;
}

以红色显示链接文本(假设它是您想要的)。

答案 2 :(得分:0)

看起来像css specificity问题,添加更具体的规则以将样式应用于锚元素

.red a{
    color:red;
}

演示:Fiddle

答案 3 :(得分:0)

类添加脚本正在运行,您必须更改您的CSS

li.red a{color:red;}

答案 4 :(得分:0)

该课程已添加。您应该将CSS应用于锚标记。

更新小提琴。

http://jsfiddle.net/wSt6Q/3/

    $(document).ready(function () {
        // Handler for .ready() called.
        $("li").on("click", function () {       
            $(this).addClass("red");
        });
    });

.red a {
    color:red;
}

答案 5 :(得分:0)

您需要阻止锚标记的默认操作。

$(document).ready(function () {
    // Handler for .ready() called.
    $("li a").on("click", function (e) {
        e.preventDefault();
        //alert( $( this ).text() );
        $(this).addClass("red");
    });
});

这是Fiddle

答案 6 :(得分:0)

另一个例子:

HTML:

<ul>
   <li data-color="red">Red</li>
   <li data-color="blue">Blue</li>
   <li data-color="green">Green</li>
</ul>

<div>
   <label>Selected Color</label>
</div>

的CSS:

.red{
   color: white;
   background: red;    
}

.blue{
   color: white;
   background: blue;
}

.green{
   color: white;
   background: green;
 }

div{
   text-align: center;
   width: 500px;
   height: 500px;
   margin: 0 auto;
}

JS:

$('li').on('click', function(){    
   var selectedColor = $(this).data('color');    
   $('div').removeClass();
   $('div').addClass(selectedColor);    
});

http://jsfiddle.net/cfVw8/