我遇到一个问题:需要尽快调用一个函数,所以我需要使用纯JavaScript编写并将其包含在头部。但是我不确定如何进行操作,因为我了解到使用.replace()会将新元素移动到页面的不同位置。 jQuery 的.replaceWith()行为非常理想。
$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");
我遇到一个问题:需要尽快调用一个函数,所以我需要使用纯JavaScript编写并将其包含在头部。但是我不确定如何进行操作,因为我了解到使用.replace()会将新元素移动到页面的不同位置。 jQuery 的.replaceWith()行为非常理想。
$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");
var image = document.getElementById('imagefiles'), parent = image.parentNode,
tempDiv = document.createElement('div');
tempDiv.innerHTML = "<input type='file' name='imagefiles' id='imagefiles' />"
var input = tempDiv.childNodes[0];
parent.replaceChild(input, image);
根据我的编辑进行修改:
var image = document.getElementById('imagefiles'), parent = image.parentNode,
input = document.createElement('input');
input.id = input.name = "imagefiles";
input.type = 'file';
parent.replaceChild(input, image);
div
?直接创建 input
会更快且代码更简洁。input = document.createElement('input'); input.type = "file"; input.id = input.name = "imagefiles";
- user1106925 const node = new DOMParser().parseFromString(html, 'text/html').body.childNodes[0];
document.getElementById(id).replaceWith(node);
let element = document.getElementById("imagefiles");
element.insertAdjacentHTML("afterend","<input type='file' name='imagefiles' id='imagefiles' />");
element.parentNode.removeChild(element);
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
.replace()
是用于字符串的。请不要在 DOM 中使用它。您能更详细地描述一下您的问题吗?您是说您希望一个元素在出现时立即被替换,而不是等待整个 DOM 准备好吗? - user1106925