0

错误线是这样的:

contxt.replaceWith(safe_copy[id]).prepend("<span class='error'>"+jsonObj.data+"</span>");

虽然该replaceWith语句工作得很好,但数据没有得到“ prepended”。

更完整的代码:

contxt = $(this).parents('div[style^="display"]');
id = $(this).attr('id');

        $.ajax({
                url: "/submit/myposts",
                type: "POST",
                data: "action=edit&post="+$(this).attr('id').match(/[0-9]+/)[0]+"&data="+encodeURIComponent(text),
                success: function(data){
                    loading.remove();
                    jsonObj = $.parseJSON(data);

                    if(jsonObj.code == "0")
                        block.html(jsonObj.data);
                    else
                        contxt.replaceWith(safe_copy[id]).prepend("<span class='error'>"+jsonObj.data+"</span>");
                },
                error: function(){
                    loading.remove();
                    contxt.replaceWith(safe_copy[id]).prepend("<span class='error'>An error occurred. Please try again.</span>");
                }
            });
4

2 回答 2

2

.replaceWith()返回原始 jQuery 对象(从页面中删除的对象),因此当您链接到它时,它将对已删除的内容进行操作,而不是添加的内容。

来自jQuery文档.replaceWith()

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

我不完全确定我理解您的代码/HTML,但这可能是一种可能的解决方法:

var newContent = $(safe_copy[id]).prepend("<span class='error'>"+jsonObj.data+"</span>");
contxt.replaceWith(newContent);
于 2012-08-08T19:47:15.857 回答
0

我怀疑以下两个问题:

a. Either the object being returned by replaceWith() was not same as the new node added, or
b. The return object was being regenerated using the original selection criteria

事实证明,您仍然拥有原始对象的句柄,该对象已从 DOM 中拉出。这在此处的文档中得到了证实。

您只需要运行选择以再次获取对新节点的引用,然后运行您的前置操作。对于您描述的场景,您不能在 replaceWith() 之前进行链接。查看以下小提琴示例,表明此方法有效:

http://jsfiddle.net/shaikhtabrez/BbgXW/7/

于 2012-08-08T20:08:45.557 回答