https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#DOMParser_HTML_extension
看起来 DOMParser 使用 innerHTML 将字符串化元素添加到 DOM。使用它有什么好处?
我在下面比较了使用 DOMParser().parseFromString() 和使用 element.innerHTML 之间的区别。我是否忽略了什么?
使用 DOMParser
const main = document.querySelector('main');
const newNodeString = '<body><h2>I made it on the page</h2><p>What should I do now?</p><select name="whichAdventure"><option>Chill for a sec.</option><option>Explore all that this page has to offer...</option><option>Run while you still can!</option></select><p>Thanks for your advice!</p></body>';
// Works as expected
let newNode = new DOMParser().parseFromString(newNodeString, 'text/html');
let div = document.createElement('div');
console.log('%cArray.from: ', 'border-bottom: 1px solid yellow;font-weight:1000;');
Array.from(newNode.body.children).forEach((node, index, array) => {
div.appendChild(node);
console.log('length:', array.length, 'index: ', index, …Run Code Online (Sandbox Code Playgroud) 我是 Node.js 的新手,在查看文档并尝试了 http.on('finish')、res.on('close') 和 res.on('end') 后,我不明白怎么每个都不一样。
http.get(url, res => {
res.setEncoding('utf8'); // returns string object to data event
res.on('data', string => {
const responseObj = responseDataList.find(responseObj => {
return responseObj.url === url;
});
responseObj.data += string;
});
res.on('close', () => {
console.log('[Interruption] connection closed before response was ended.'); // Never fires
})
res.on('error', console.error);
// TODO: find out difference between response.end and response.close and http.finish events
res.on('end', (data, encoding) => {
// Seems to fire at the same time …Run Code Online (Sandbox Code Playgroud)