问题描述
下面是两段代码,由于某种原因,没有任何事情发生,但来自同一个JS文件的其他jQuery函数在UL页面上执行得很好,这是否正在盯着我呢! p>
< ul id =activityPaganationclass =paganation>
< li> 1< / li>
< li>< a href =#> 2< / a>< / li>
< li>< a href =#> 3< / a>< / li>
< li>< a href =#> 4< / a>< / li>
< li>< a href =#> 5< / a>< / li>
< li>< a href =#> 6< / a>< / li>
< / ul>
$ b $(document).ready(function(){
$('#activityPaganation li a')。on(click,function(e ){
e.preventDefault();
var pid = $(this).text();
alert(pid);
});
});
您可以使用事件委托,因为这是动态添加的(文件).on(click,#activityPaganation li a,function(e){to {$}
e.preventDefault();
var pid = $(this).text();
alert(pid);
});
而不是文档在任何时间点使用DOM中存在的某个容器。
如果添加了li,并且您的 ul
#activityPaganation
随时存在然后:
$('#activityPaganation')。on(click,li a,function(e){
e.preventDefault();
var pid = $(this).text();
alert(pid);
});
否则将您的事件绑定到加载的完成
回电。
$('something') ();
e.preventDefault();
('someurl',function(){
$('#activityPaganation li a')。 var pid = $(this).text();
alert(pid);
});
});
原因在于,在元素上直接绑定事件需要在DOM中存在,相反,解决方法是将事件委托给存在于DOM中的任何点或文档头的容器,以便将来添加when元素时,它将获取从其父级委派的事件。实际上,它使用事件冒泡来达到此效果。
Below are the two snippets of code, for some reason nothing is happening, yet other jQuery functions from the same JS file are executing fine on the page with the UL, is it something that's staring me in the face!?
<ul id="activityPaganation" class="paganation">
<li>1</li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">6</a></li>
</ul>
$(document).ready(function() {
$('#activityPaganation li a').on("click", function(e) {
e.preventDefault();
var pid = $(this).text();
alert(pid);
});
});
You can use event delegation, since this is dynamically added to DOM.
$(document).on("click", "#activityPaganation li a", function(e) {
e.preventDefault();
var pid = $(this).text();
alert(pid);
});
instead of document use some container that exists in DOM at any point in time.
if the li's are added and your ul
#activityPaganation
exists at any time then:
$('#activityPaganation').on("click", "li a", function(e) {
e.preventDefault();
var pid = $(this).text();
alert(pid);
});
otherwise move your event binding to the load's complete
call back.
i.e
$('something').load('someurl', function(){
$('#activityPaganation li a').on("click", function(e) {
e.preventDefault();
var pid = $(this).text();
alert(pid);
});
});
Reason is that with direct event binding on the element it needs to exist in DOM, instead workaround is to delegate the event to a container that exists in DOM at any point or document head so that the when element is added in future it gets the event delegated from its parent. Effectively it uses event bubbling for this effect.
这篇关于单击问题:动态生成的链接不触发点击功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!