简体   繁体   English

Jquery 如何在未在列表中指定事件的情况下触发 function

[英]Jquery How to trigger function on without specifying events in the list

I have a list of items and can be removed by clicking.我有一个项目列表,可以通过单击删除。

I need the first item to be the highlight only when there is one item on the list.只有当列表中有一个项目时,我才需要第一个项目成为亮点。 I have tried to do that by the click event.我试图通过点击事件来做到这一点。 However, would it be possible to do it without.click()?但是,没有.click() 可以做到吗? (or any other events). (或任何其他事件)。 The reason is that this list is dynamically interacting with other lists that the list item may change by other functions.原因是该列表与其他列表动态交互,列表项可能会被其他函数更改。

In other words, the list is dynamically changing, could jquery keep checking whether there is only one item on the list (without specifying specific event trigger)?换句话说,列表是动态变化的,jquery 是否可以一直检查列表中是否只有一项(不指定具体事件触发)?

<ul id="container">
<li>1</li>
<li class="fixed">2</li>
<li>3</li>
<li class="fixed">4</li>
<li>5</li>
</ul>

$('#container').delegate('li', 'click', function() {
  $(this).remove();
});


$('#container').click(function(){
  if ($('#container').children().length == 1) {
    $("#container li:first-child" ).css( "background-color", "#fff2ac" );
  }
}

You can do this purely with CSS with a rule that checks if the li is both the :first-child AND the :last-child -您可以纯粹使用 CSS 执行此操作,并使用一条规则检查li是否既是:first-child又是:last-child -

 .container li:first-child:last-child { background-color: red; }
 <h5>List With Many Items</h5> <ul class="container"> <li>1</li> <li class="fixed">2</li> <li>3</li> <li class="fixed">4</li> <li>5</li> </ul> <h5>List With One Item</h5> <ul class="container"> <li>1</li> </ul> <h5>List With Two Items</h5> <ul class="container"> <li>1</li> <li class="fixed">2</li> </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM