php - 在附加的 HTML 上使用 jQuery 效果

标签 php javascript jquery html css

我的代码在这里。

// HTML Code
<div class="article"></div>

// jQuery
$('.article').append('<a href="" class="toggle">Toggle div</a>');

是否可以使用新创建的 href 链接并像这样切换 div:

// jQuery
$('.toggle').click(function() { 
   $('.article').toggle('slow');
});

我试过上面的方法,但没有成功。我刚刚被重定向到索引页面。

最佳答案

不要使用 click() : 它已被弃用,即使不是,也不会工作。使用 on() :

$('.toggle').on('click', function() { 
   $('.article').toggle('slow');
});

此外,更改您的 a标记为 <a href="javascript:void(0)" class="toggle">Toggle div</a> .


至于为什么on()作品和click()不会,你需要阅读 jQuery 的文档。简而言之,点击事件已经绑定(bind)到页面上的一个元素上;此范围不涵盖添加到 DOM 的 future 元素。 On() ,但是,是委托(delegate)事件:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

关于php - 在附加的 HTML 上使用 jQuery 效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14428036/

相关文章:

php - 约定表名(带下划线)

php - PHP 的 pthreads 不在 Apache 中执行并行线程

javascript - 使用 MutationObserver 时获取当前 MutationRecord 的新属性值?

javascript - 遍历 table > tr > td > div 下的每个跨度

ruby-on-rails-3 - 轨道 3 : Ajax and the <%= escape_javaScript(item) %>

jquery - 如何使用 jQuery 在表格中间添加行?

php - 具有长 URI 的 Android HttpPost

php - Mysql插入查询,未知错误

javascript - 错误 [prerender-spa-plugin] - 无法预呈现所有路线

javascript - 用 Javascript 获取电子邮件地址的每个附件