如何用jQuery替换HTML但保留事件绑定 [英] how to replace HTML with jQuery but keep event bindings

查看:96
本文介绍了如何用jQuery替换HTML但保留事件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个具体的问题,而是更具战略意义的问题,但我认为正是这样问的:

假设我有一个页面或ap包含3个单独的部分.表单的一部分更改将ajax发布发送到服务器,这需要在第二部分中进行更改.我想发回第2节的经过重新处理的HTML输出,并将其替换为第2节的原始状态

但是,第2节中的许多元素都有更改,单击,拖动等绑定-从经验上,当我执行html替换时,我会丢失所有绑定.

但是,这使我不得不分别重写第2节中许多元素中的某些内容,以免丢失绑定.

知道,有一个更简单的方法可以解决,这似乎是一个常见问题.谁能为我提供这个问题的啊哈"部分,也许还有一些例子或链接?我真的很感激.

解决方案

您需要将问题分为两部分

处理事件
可以使用 $ .on()使用事件委托来完成.即,不是在元素上注册事件,而是在不会删除的父元素上注册
例如:

$('.container').on('click', 'a', function(){
    //do something
})

处理可拖动的小部件
在这里,我认为您很不走运,因为一旦添加了新的dom元素,除了重新初始化这些小部件,我看不到其他任何方法
例如:

var ct = $('.container').html('');
ct.find('li').draggable({})

this is more a strategic question than a specific one, but I think it's precisely asked so here goes:

let's say I have a page or ap that has 3 separate sections. A change on part of the form sends an ajax post to the server, and this requires a change in section two. I want to send back the re-processed HTML output of section 2, and have this replace the original state of section 2

but, section 2 has many elements that have change, click, drag etc. bindings - and from experience when I do a html replace, I lose all my bindings.

HOWEVER, this leaves me with rewriting certain things in many of the elements in section 2 individually so as not to lose the bindings.

I KNOW there's an easier approach to this, seems like a common problem. Can anyone provide me with the "aha" part of this question, and perhaps a few examples or links? I really appreciate it.

解决方案

You will need to divide the problem into two sections

Handling events
This can be done using event delegation using $.on(). ie instead of registering events on the element you register on a parent which will not be removed
Ex:

$('.container').on('click', 'a', function(){
    //do something
})

Handling widgets like draggable
Here I think you are out of luck because I don't see any other way than to reinitialize those widgets once the new dom elements are added
Ex:

var ct = $('.container').html('');
ct.find('li').draggable({})

这篇关于如何用jQuery替换HTML但保留事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆