【问题标题】:jQuery .on("click") - alternative to .live()jQuery .on("click") - 替代 .live()
【发布时间】:2013-08-07 13:41:44
【问题描述】:

在我的项目中,我将几个按钮附加到一个 div:

$(".tab-content").append("<div class='landing_content'><button class='off-screen-nav-button btn btn-info btn_edit' data-effeckt='effeckt-off-screen-nav-right-overlay'>Edit</button></div>");

然后使用以下代码监听点击:

$(".tab-content").on("click",".btn-edit",function(){
  console.log('edit');
});

为什么这不起作用?我习惯使用 .live() 但它已被弃用。

谢谢。

【问题讨论】:

  • 在绑定处理程序时,“.tab-content”元素必须在 DOM 中。并修复您的选择器或类名
  • btn_editlanding_content 对于类/ID 名称无效,因为下划线无效/不支持(奇怪的是在某些 IE 版本中除外)

标签: javascript html jquery jquery-on


【解决方案1】:

在你的标记中有btn_edit,在你的jQuery中有btn-edit

更改您的标记 class 以匹配 jQuery 选择器,如下所示:

$(".tab-content").append("<div class='landing_content'><button class='off-screen-nav-button btn btn-info btn-edit' data-effeckt='effeckt-off-screen-nav-right-overlay'>Edit</button></div>");

【讨论】:

  • 哈哈哈 :D 抱歉。总是很高兴能有一双新鲜的眼睛。有时您可能会迷失在所有代码中。
  • @CasperSlynge - 不用担心,有时您盯着自己的代码越多,它看起来就越正确,而弄清楚它为什么会被破坏就越令人沮丧。这就是 StackOverflow 的用途。 :-)
【解决方案2】:

您的方法不起作用的原因(除了关于btn-edit 指出的内容)可能是因为您试图将事件绑定到在DOM 中实际不存在的元素,直到它被附加之后,曾经有 LIVE 已被贬值,但您可以这样做:

//bind the event to the document which always exists and specify the selector
//as the second argument 
$(document).on("click",".tab-content .btn-edit",function(){
    console.log('edit');
});

希望这有助于查看文档here 上的 jQueries 以获得更多帮助。

【讨论】:

  • @CasperSlynge 你对什么感到抱歉? :S
  • 为了上面的答案。
猜你喜欢
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多