我的代码在这里。
// 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/