绑定Jquery事件通过其他事件生成的元素

编程入门 行业动态 更新时间:2024-10-18 06:00:29
本文介绍了绑定Jquery事件通过其他事件生成的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在通过另一个动作创建的项目上绑定jquery事件时遇到问题,例如,当加载更多链接时,点击

元素列表< div class =itmid =c_1>< / div> < div class =itmid =c_2>< / div> ....

点击加载更多链接时,它会生成更多元素,例如

< div class =itmid =c_11>< / div> < div class =itmid =c_12>< / div> ...

在页面加载时,我使用下面的jquery脚本来绑定鼠标进入并离开事件。

$('。itm')。on({ mouseenter:function(e ){ alert('mouse enter'); }, mouseleave:function(e){ alert('mouse leave'); } });

这将成功应用元素c_1,c_2上的事件,但是当加载更多链接调用时,它会生成更多元素。为此,我解除绑定悬停事件并将其绑定一次,一旦在点击加载更多链接时调用的函数下创建了新元素。

$( (')'; $($'$'); $($'$'$'$'); ).off(); //绑定一次 $('。itm')。on({ mouseenter:function(e){ alert('mouse enter '); }, mouseleave:function(e){ alert('mouse leave'); } }); }) ;

已经载入更多元素并在页面上正确显示,但仍然悬停事件正确调用已经创建了元素,而不是通过加载更多事件创建的元素。

任何人都可以帮助我正确地将事件附加到通过调用其他jQuery事件动态创建的元素上或

解决方案

在动态内容中,您需要委派代码,如下所示:

$(document).on({ mouseenter:function(e){ alert('mouse enter'); } , mouseleave:function(e){ alert('mouse leave'); } },'.itm');

您应该将文档替换为最接近的父文件没有用Ajax插入。

I am facing problem on binding jquery event on items created through another action e.g when load more link clicked

e.g there are list of elements <div class="itm" id="c_1"></div> <div class="itm" id="c_2"></div> ....

When click on load more link, it will generate more elements e.g

<div class="itm" id="c_11"></div> <div class="itm" id="c_12"></div> ...

At page load time, i am using the following jquery script to bind mouse enter and leave event.

$('.itm').on({ mouseenter: function (e) { alert('mouse enter'); }, mouseleave: function (e) { alert('mouse leave'); } });

This will successfully apply event on elements c_1, c_2 but when load more link call, it will generate more elements. for this i unbind hover events and bind it again once new elements created under function called when load more link clicked.

$(".cmtldmore").on('click', function (e) { // Ajax process to load more elements in tray. // Unbind hover event $('.itm').off(); // Bind it again $('.itm').on({ mouseenter: function (e) { alert('mouse enter'); }, mouseleave: function (e) { alert('mouse leave'); } }); });

Both already and load more elements display properly on page, But still hover events properly call on already create elements, but not on elements created by "load more" event.

Can any one help me properly attach event on elements created dynamically through calling other jquery events or functions.

解决方案

On dynamic content you will need to delegate, something like this:

$(document).on({ mouseenter: function (e) { alert('mouse enter'); }, mouseleave: function (e) { alert('mouse leave'); } }, '.itm');

You should replace document with the closest parent that is not inserted with Ajax.

更多推荐

绑定Jquery事件通过其他事件生成的元素

本文发布于:2023-11-27 21:57:16,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   绑定   元素   Jquery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!