在职能上: const htmlCollection = document.getElemenetsByClassName('elemenet-class')
用于从DOM中获取所需的元素,而一些元素的属性则用于函数(return htmlCollection[0].clientWidth
).
问题是在所有DOM节点被加载之前,函数的返回就会被执行,所以当我访问了 htmlCollection[0]
得偿所愿 element
,它得到 undefined
. 我尝试的是将代码封装在 setTimeout
与 500ms
偏移,我可以访问 htmlCollection[0]
元素,但现在的问题是,函数的返回是主线程的一部分,在整个的 setTimeout
是异步操作,所以 htmlCollection[0].clientWidth
的函数 "lives "的返回值中,应该只有在函数 "lives "中才有。setTimeout
.
我怎样才能 "等待 "DOM被加载(或 "等待 "setTimeout执行和检索。contentWrapperWidth
),然后执行函数的返回?
的代码,在函数中,const htmlCollection = document.getElemenetsByClassName('elemenet-class')是用来从DOM中获取所需元素的,一些元素的属性也是如此。
// first try (fails because on function return, 'content-wrapper' is not loaded in DOM)
renderPreview = () => {
let htmlString = getHTML();
const contentWrapper = document.getElementsByClassName('content-wrapper');
const contentWrapperWidth = contentWrapper[0].clientWidth;
htmlString = htmlString.replace('width_placeholder', contentWrapperWidth);
return htmlString;
}
// second try (fails because function's return executes before setTimeout of course - i.e. contentWrapperWidth lives only inside setTimeout and function returns htmlString with placeholder, before replacing)
renderPreview = () => {
let htmlString = getHTML();
setTimeout(() => {
const contentWrapper = document.getElementsByClassName('content-wrapper');
const contentWrapperWidth = contentWrapper[0].clientWidth;
htmlString = htmlString.replace('width_placeholder', contentWrapperWidth);
} , 500);
return htmlString;
}
你可以使用 document.addEventListener("load", function)
这应该在dom加载后加载你的函数。