如何使类自动应用于 UL 内的所有新 LI 元素

  • 本文关键字:LI 元素 何使类 应用于 UL jquery
  • 更新时间 :
  • 英文 :


使用 jQuery 的事件委托 (http://learn.jquery.com/events/event-delegation),我能够将事件自动附加到添加到 UL 的 LI 元素上,如以下代码所示:

http://jsfiddle.net/Betum

但是如何自动添加样式呢?

<html>
<head>
    <title>test</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
    $(function() {
        $("ul#list").append('<li>added before</li>');
        //assures that any new LI added to LIST will have this click event
        $("ul#list").on("click","li", function() {
            $(this).addClass("selected");
        });
        //how to also assure that any LI added to LIST will have this style
        $("ul#list li").addClass("original");
        $("ul#list").append('<li>added after</li>');
    });
    </script>
    <style type="text/css">
        li.original {
            color: red;
            cursor: pointer;
        }
        li.selected {
            color:green;
        }
    </style>
</head>
<body>
    <div id="container">
        <ul id="list">
            <li>one</li>
            <li>two</li>
            <li>three</li>
            <li>four</li>
        </ul>
    </div>
</body>

保持简单。将单个类应用于<ul>并基于该类编写 CSS,而不依赖于<li>上的任何特定类。例如:

ul.someClass > li {
    color: red;
    cursor: pointer;
}

不需要额外的JavaScript。

添加类

您可以使用.addClass()将类添加到新创建的元素中

$("ul#list").append($('<li>added after</li>').addClass("original"));

或者只是在创建元素时手动编写:

$("ul#list").append('<li class="original">added after</li>');

jsFiddleDemo

<小时 />

替代方法:使 CSS 选择器更通用

还可以使用 original 类作为 ul 内所有列表项的默认类。

li {
    color: red;
    cursor: pointer;
}
li.selected {
    color:green;
}

jsFiddleDemo

最新更新