如何使用js重新加载特定元素

how to reload a specific element with js

我只是想知道如何使用 javascript 代码重新加载特定元素或 div。

div:

<div id="profile_img">
   <figure>
      <img id="holla" src="avatar.gif"/>
   </figure>
</div>

希望你能有所帮助。我真的需要它。谢谢

您可以在JS中轻松设置图片来源:

document.getElementById("holla").src = "avatar.gif";

function refresh() {
document.getElementById("holla").src = "avatar.gif";
}
<div id="profile_img">
   <figure>
      <img id="holla" src="avatar.gif"/>
   </figure>
</div>
<button onclick="refresh();">Refresh Image</button>

如果您尝试从服务器重新加载,那么您可以执行 ajax 调用并将响应设置为 div。 document.getElementById('holla').innerHTML = this.responseText;

您必须有某种机制来加载图像。 Ajax 调用将异步加载图像。

// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function
xhttp.onload = function() {
  //you get response back from server in responseText.
  document.getElementById('holla').innerHTML = this.responseText;
}
// Send a request
xhttp.open("GET", "ajax_info.txt");// path to file
xhttp.send();