如何在使用outerHTML更改内容后引用新的DOM对象?

我有一个部门,我需要在事件上更改其外部HTML。 问题是在设置outerHTML我无法引用新选择的DOM对象,除非我再次明确地捕获它。

有没有办法在调用outerHTML时直接更新变量引用(在我的例子中是下面的div变量的引用)?

 $("#changeDiv").click(function(){ var div = $(this).prev(); div[0].outerHTML = `

World

`; console.log(div); // logs [div#imFirstDiv, prevObject: n.fn.init[1], context: button#changeDiv] // the following line does not affect the newly added division // since the var `div` references the old DOM object // unless I add div = $(this).prev(); before setting the html of // the paragraph it will not set it div.find('p').html('Override'); });
  

Hello

正如您所看到的那样,更改outerHTML会使事情表现得有些奇怪,因为您正在完全替换原始元素,但仍然引用旧元素。

最好创建一个新的div ,然后在旧的div之后添加它after()然后remove()旧的div 。 这可以将div的位置保持在正确的位置。

 $("#changeDiv").click(function(){ // get the oldDiv var oldDiv = $(this).prev(); // Create a newDiv var newDiv = $('

World

'); // add newDiv after oldDiv one, then remove oldDiv from the DOM. oldDiv.after(newDiv).remove(); // now you still have the reference to newDiv, so do what you want with it newDiv.find('p').html('Override'); });
  

Hello

我通过获取将要替换的标记的引用元素(兄弟或父级)来解决这个问题。

这是一个函数,它不依赖于您要更改的元素:

 function replaceElement(ele, outerHTML) { var parent = false, refEle; //if element that's going to be changed has previousElementSibling, take it as reference. If not, the parentElement will be the reference. if (ele.previousElementSibling !== null) refEle = ele.previousElementSibling; else { refEle = ele.parentElement; //indicate that parentElement has been taken as reference parent = true; } //change the outerHTML ele.outerHTML = outerHTML; //return the correct reference if (parent) return refEle.firstElementChild; else return refEle.nextElementSibling; } 

所以在你的情况下,你会这样调用它:

 div[0] = replaceElement(div[0], '

World

');

我希望它也适用于jQuery,因为我只用原生javascript编写所有脚本。