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

KAD*_*KAD 10 html javascript jquery

我有一个部门,我需要在发生事件时更改其外部 HTML。问题是,设置后outerHTML我无法引用新选定的 DOM 对象,除非我再次显式捕获它。

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

$("#changeDiv").click(function(){

  var div = $(this).prev();
  div[0].outerHTML = `<div id="imSecondtDiv"> <p> World </p> </div>`;
  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'); 

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imFirstDiv"> <p> Hello </p> </div>
<button id="changeDiv" >Change Div 1</button>
Run Code Online (Sandbox Code Playgroud)

Rhu*_*orl 2

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

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

$("#changeDiv").click(function(){

  // get the oldDiv
  var oldDiv = $(this).prev();

  // Create a newDiv
  var newDiv = $('<div id="imSecondtDiv"> <p> World </p> </div>');

  // 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'); 

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imFirstDiv"> <p> Hello </p> </div>
<button id="changeDiv" >Change Div 1</button>
Run Code Online (Sandbox Code Playgroud)

使用外部HTML

如果你确实需要使用outerHTML,你可以简单地$(this).prev()再次获取:

$("#changeDiv").click(function(){

  var div = $(this).prev();
  div[0].outerHTML = `<div id="imSecondtDiv"> <p> World </p> </div>`;

  // the "new" div is now before the button, so grab the reference of THAt one
  div = $(this).prev();

  // 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'); 

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imFirstDiv"> <p> Hello </p> </div>
<button id="changeDiv" >Change Div 1</button>
Run Code Online (Sandbox Code Playgroud)