JQuery替换DOM节点

需求描述:

Ajax获取的数据是一段Html代码并将原来DOM节点对应的内容替换掉。

如:获取到的内容为

<div><div class='one'>
  <div class='c'></div>
  <div class='d'></div>
</div> </div>

原有DOM节点:

<div class='one'>
  <div class='a'></div>
  <div class='b'></div>
</div>

实现:

$body.on('click', '.product-wrap .hover-panel .colors li', function () {
            var $this = $(this);

            $.ajax({
                url: getUncachedUrl($this.data('url')),
                type: 'POST',
                success: function (data) {
                    $this.closest('.one').html($('.one', data).html());
                }
            });
            return false;
        });

遇到的问题及注意:

1、若当页面的节点是通过Ajax添加的,那么不能通过类选择器直接为其绑定事件。

2、$this.closest('.a').html($('.a', data).html()); 替换DOM节点内容函数

3、JQuery不能直接替换最外层div。也就是说,当.one为最外层div时,不能实现替换。


猜你喜欢

转载自blog.csdn.net/weixin_41355260/article/details/80220983