简体   繁体   English

在附加的HTML上使用jQuery效果

[英]Using jQuery effects on appended HTML

I have my code here. 我的代码在这里。

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

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

Is it possible to use that newly created href link and toggle a div like this: 是否可以使用新创建的href链接并切换这样的div:

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

I have tried the above with no luck. 我已经尝试过以上没有运气了。 I just get redirected to index page. 我只是被重定向到索引页面。

Don't use click() : it's deprecated and wouldn't work even if it weren't. 不要使用click() :它已被弃用,即使它不是也不会工作。 Use on() : 使用on()

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

Also, change your a tag to <a href="javascript:void(0)" class="toggle">Toggle div</a> . 另外,将您a标签更改为<a href="javascript:void(0)" class="toggle">Toggle div</a>


As to the reason why on() works and click() doesn't, you need to read jQuery's documentation. 至于on()工作原理和click()没有,你需要阅读jQuery的文档。 In short, the click event has been bound to an element on the page; 简而言之,click事件已绑定到页面上的元素; this scope does not cover future elements that are added to the DOM. 此范围不包括添加到DOM的未来元素。 On() , however, is a delegated event: 但是, On()是一个委托事件:

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. 通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委派事件来避免频繁附加和删除事件处理程序的需要。

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

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