如何更改以下功能以在文档就绪时触发而不是单击?我最初删除了按钮并将el.addEventListener('click', function()
更改为document.ready(function()
,但不确定我错过了什么。
//when button clicked, event listener triggered(needs to be removed so this
//functions ONLY on page load
var el = document.getElementById('button');
var getFontFamily = function(){
for(var i = 0; i < document.styleSheets.length; i++){
for(var j = 0; j < document.styleSheets[i].rules.length; j++){
if(document.styleSheets[i].rules[j].style.fontFamily){
return document.styleSheets[i].rules[j].style.fontFamily;
}
}
}
return 'not-found';
};
//Sends event to receiving page to change font of iframed page.
//needs to work on document.ready, not be triggered by button click on parent page
el.addEventListener('click', function(){
var data = getFontFamily();
window.frames[0].postMessage(data, 'http://localhost:3000');
console.log('Message sent -->');
});
接收帖子消息的页面
window.addEventListener('message', function(e){
document.body.style.fontFamily = e.data;
console.log('<---Message received');
}, false);
如何在页面准备好后触发?
答案 0 :(得分:0)
如果你想要一个函数在加载时执行而你没有使用jQuery,你可以为DOMContentLoaded
事件添加一个事件监听器。
window.addEventListener('DOMContentLoaded', function(){
var data = getFontFamily();
window.frames[0].postMessage(data, 'http://localhost:3000');
console.log('Message sent -->');
})