简体   繁体   English

点击使用jQuery从UL中删除LI

[英]Remove LI from UL on click using jQuery

So I have a INPUT TEXT that upon keypress=enter prepends an LI to an UL 所以我有一个INPUT TEXT,在keypress =输入时,将一个LI预先设置为UL

The LI contains a LINK that gives the user the option to remove it from the UL LI包含LINK,用户可以选择将其从UL中删除

HTML (on page load) HTML(在页面加载时)

<ul id="conditionList"></ul>

after ther user inputs some conditions, the UL gets populated with LI 在用户输入一些条件之后,UL将填充LI

<li>condition<a href="#" class="clearitem">x</a></li>

However, in my jQuery 但是,在我的jQuery中

$('#conditionList a.clearitem').click(function(){
$(this).parent().remove();
});

will not work! 不管用!

Is it because it's not recognizing the new LI's? 是因为它没有认识到新的LI?

Deprecated since 1.9. 自1.9以来已弃用。 use on instead of live . 使用on ,而不是live

Use live() instead of click there because your link is generated dynamically: 使用live()而不是click那里,因为您的链接是动态生成的:

$('#conditionList a.clearitem').live('click', function(){
  $(this).parent().remove();
});

.live() 。生活()

Attach a handler to the event for all elements which match the current selector, now or in the future. 现在或将来,为当前选择器匹配的所有元素附加处理程序。

Depracate since 1.9. 自1.9以来被剥夺。 use on instead of live . 使用on ,而不是live

You need to use an event binding that's going to recognize created elements. 您需要使用将识别已创建元素的事件绑定。 This should do that: 这应该这样做:

$('#conditionList a.clearitem').live('click', function () {
  $(this).parent().remove();
});

Possibly the LIs are added to the DOM after the click event handler has been declared? 在声明了click事件处理程序后,可能会将LI添加到DOM中? If so, you might want to look into using live() instead of bind(): 如果是这样,您可能希望使用live()而不是bind():

$('#conditionList a.clearitem').live('click', function(){
$(this).parent().remove();
});

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

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