标记动态可扩展列表中的项目

时间:2015-12-12 15:50:39

标签: javascript jquery html css

我想在列表中标记一个点击的项目。这工作正常(test1 - test5) - 但是如果我通过JQuery的追加添加一些项目(例如test6)到该列表,只有加载页面时那里的test1-test5,“使用”突出显示的css功能。我怎么能解决这个问题?

$("#tracklist li").on("click", function() {
  $('.highlight').removeClass('highlight');
  $(this).addClass('highlight');
});

$("#test").click(function() {
      $("#tracklist").append("<li class='list_style_tracklist_lastitem ui-sortable-handle'><a href='#'>test6</a></li>");
    }
ol {
  list-style-type: none;
  margin: 0;
  padding: 0;
  height: 120px;
  width: 450px;
  overflow-y: auto;
  overflow-x: hidden;
  background: #e6e6e6;
}
li {
  font: 200 15px/1.5 Helvetica, Verdana, sans-serif;
  border-bottom: 1px solid #ccc;
  border: 1px solid #d3d3d3;
  background: #e6e6e6;
  font-weight: normal;
  padding: 0em 0em 0em 1.5em;
  text-indent: 0.1em;
  list-style: none;
  background-repeat: no-repeat;
}
.list_style_tracklist_music {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAQAAABKIxwrAAAAvElEQVR4AWMgDygz2DLYoEOgmDYDMzblEQxzGGZhgRMZHBiYsCufiQmBGibBNRBWjtBAUDnzLEaEBnMCyllnNR3QWMwwA8QGykUSUM4xe90lixVw5RHDVfkMxplcxCoXmJO7c9OVQ3euPjNdTlA595xVF3/9+Q8ELz7qLCGkfIb64ifvQYo/fus7yjILKILfdJZZ8Vvmnek/6rGGFayYsFdnAOF0sDMIK0dAKiufhQuClRPOq4g8C5QnBwAAiy7V4BTvo9kAAAAASUVORK5CYII=');
}

ol li.list_style_tracklist_music a,
ol li.list_style_tracklist_video a,
ol li.list_style_tracklist_lastitem a {
  text-decoration: none;
  color: #000;
  /*-moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    user-select: none;*/
  -webkit-transition: font-size 0.3s ease, background-color 0.3s ease;
  -moz-transition: font-size 0.3s ease, background-color 0.3s ease;
  -o-transition: font-size 0.3s ease, background-color 0.3s ease;
  -ms-transition: font-size 0.3s ease, background-color 0.3s ease;
  transition: font-size 0.3s ease, background-color 0.3s ease;
  display: block;
  width: 450px;
}
ol li.list_style_tracklist_music a:hover,
ol li.list_style_tracklist_video a:hover,
ol li.list_style_tracklist_lastitem a:hover {
  /*font-size: 18px;*/
  background: #ffbb99;
}
.highlight {
  background-color: #ffbb99;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="tracklist">
  <li class="list_style_tracklist_music">
    <a href="#">test1</a>
  </li>
  <li class="list_style_tracklist_music">
    <a href="#">test2</a>
  </li>
  <li class="list_style_tracklist_music">
    <a href="#">test3</a>
  </li>
  <li class="list_style_tracklist_music">
    <a href="#">test4</a>
  </li>
  <li class="list_style_tracklist_music">
    <a href="#">test5</a>
  </li>
</ol>
<input type="button" name="test" value="test" id="test" />

1 个答案:

答案 0 :(得分:1)

首先您将功能绑定到现有的<li> 然后你创建了一个新的<li>(test6),显然没有绑定!

这里更简单的是将绑定委托给父<ol>,因此它的任何子节点一旦存在就会立即涉及:

$("#tracklist ol").on("click", function(e) {
  $('.highlight').removeClass('highlight');
  $(e.target).addClass('highlight');
});