javascript jQuery replaceWith 查找新元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6118778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:33:34  来源:igfitidea点击:

jQuery replaceWith find new element

javascriptjquery

提问by C. Ross

I'm writing a script to replace some images with divs in jQuery. I'm currently using the replaceWith()method, which works fine, but returns the original (removed) element instead of the new element.

我正在编写一个脚本来用 jQuery 中的 div 替换一些图像。我目前正在使用该replaceWith()方法,该方法工作正常,但返回原始(已删除)元素而不是新元素。

The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the originaljQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

.replaceWith() 方法与大多数 jQuery 方法一样,返回 jQuery 对象,以便其他方法可以链接到它上面。但是,必须注意的是,返回的是原始jQuery 对象。这个对象指的是从 DOM 中删除的元素,而不是替换它的新元素。

How can I get a reference to the new DOM element I just created?

如何获得对我刚刚创建的新 DOM 元素的引用?

回答by qwertymk

$.fn.replaceWithPush = function(a) {
    var $a = $(a);

    this.replaceWith($a);
    return $a;
};

See a working demo

查看工作演示

回答by eaolson

I believe replaceAll() returns the new content. It has the target and source reversed from replaceWith().

我相信 replaceAll() 会返回新内容。它具有从 replaceWith() 反转的目标和源。

var newobj = $( "<p>New paragraph" ).replaceAll( "#replaceme" );

回答by mindchasers

Precede your call to replaceWith() with a jQuery call to find the parent node and then use the parent to find the new node that was inserted with the replaceWith() function.

在调用 replaceWith() 之前使用 jQuery 调用查找父节点,然后使用父节点查找使用 replaceWith() 函数插入的新节点。

Here's an example inside the success handler of a $.ajax() function that replaces a form:

这是替换表单的 $.ajax() 函数的成功处理程序中的示例:

success: function(data,textStatus,jqXHR){
    var $li=$form.parents('li');        
    $form.replaceWith(data);
    var $form=$li.find('form');
    //...
},

In this example, there was a unique form for each li. You may need to tailor your approach depending on how you construct your DOM.

在这个例子中,每个 li 都有一个独特的形式。您可能需要根据您构建 DOM 的方式来定制您的方法。