html重绘后,Jquery函数无法正常工作[重复](Jquery functions not working after html redraw [duplicate])

编程入门 行业动态 更新时间:2024-10-28 18:33:13
html重绘后,Jquery函数无法正常工作[重复](Jquery functions not working after html redraw [duplicate])

这个问题在这里已有答案:

动态创建元素的事件绑定? 23个答案

我的问题:在重新绘制激活这些处理程序的HTML元素后,单击处理程序无法正常工作。

我有一个父div,其中包含可通过jquery的.sortable()方法排序的子div列表。 这些div具有各种点击处理程序,可以执行各种操作。

jsfiddle: http : //jsfiddle.net/GA4Qs/805/

首先,我收集父div中的所有html

var original_order = $('#sortable_groups').html()

然后在取消时,将HTML恢复到原始状态

$('#cancel').click(function() { $('#sortable_groups').empty().html(original_order); });

重绘工作与我想要的完全一样,但在我取消并重新绘制html后,点击处理程序无法正常工作。

在深入挖掘SO之后,我发现了一些关于“直播”事件的过时帖子,这些事件已合并到.on('click')事件中。 我已经更新了代码以使用.on()处理程序而不是.click(),遗憾的是这并没有解决问题。

我上面的小提琴简化了(但显示)我遇到的问题。 如果单击粗体文本,则会显示完整性警报。 点击“取消”后,通过点击触发的健全警报不再出现。

我有一种感觉,这个问题很可能是我对Jquery的某些方面的误解,但是由于一切似乎最初都运行良好,并且控制台中没有错误,我不确定下一步该尝试什么。

This question already has an answer here:

Event binding on dynamically created elements? 23 answers

My issue: click handlers are not working after I redraw the HTML elements that activate these handlers.

I have a parent div with a list of child divs that are sortable via jquery's .sortable() method. These divs have a variety of click handlers that cause various actions to happen.

jsfiddle: http://jsfiddle.net/GA4Qs/805/

First I collect all the html in the parent div

var original_order = $('#sortable_groups').html()

and then on cancel, restore the HTML to it's original state

$('#cancel').click(function() { $('#sortable_groups').empty().html(original_order); });

The redrawing works exactly like I want it to, but after I cancel and the html is redrawn, the click handlers aren't working.

After digging through SO, I found some outdated posts about 'live' events, which have merged into .on('click') events. I have updated the code to use .on() handlers instead of .click(), sadly this did not solve the problem.

My above fiddle simplifies (but shows) the issue I'm having. If you click the bold text, a sanity alert appears. After hitting 'cancel', the sanity alert triggered via a click no longer appears.

I have a feeling that this issue is likely to do my misunderstanding of some aspects of Jquery, but as everything appears to work well initially and no errors are present in the console, I'm not really sure what to try next.

最满意答案

用于动态元素的委托

$('#sortable_groups').on('click', '.dg_acc_div' , function(e){ window.alert($(this).html()) });

小提琴: http : //jsfiddle.net/GA4Qs/807/

use on delegation for dynamic element

$('#sortable_groups').on('click', '.dg_acc_div' , function(e){ window.alert($(this).html()) });

fiddle: http://jsfiddle.net/GA4Qs/807/

更多推荐

本文发布于:2023-07-30 02:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1321656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法正常   函数   工作   Jquery   重绘后

发布评论

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

>www.elefans.com

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