我已经完成了一个脚本,该脚本在包含电子邮件所在的textarea的页面上运行。
我在此页面上做了很多事情,但其中一个是基于所选数字加载iframe,然后iframe加载后从此页面获取我需要的相关详细信息。
我已经在一个名为frameLoaded的函数中编写了这个代码,并且我将其设置为onload事件,但脚本仍然运行到一个无法找到的错误。元素的innerHTML。
如果我加载iframe然后执行此脚本它可以正常工作,但是如果我尝试加载iframe并一起执行脚本,那么它会运行到此错误。
以下是我使用的代码:
//Getting text currently in the textarea
var selectedTxt = document.getElementById('txtEmailText').value;
//Converting it to a string - this is just for troubleshooting purposes that I've used two variables
var insertText = selectedTxt.toString();
//Loads in the highlighted purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
//Declares global variables to hold the title and number
var purchaseTitle;
var purchaseNumber;
//Function to execute code to grab title and number once the frame has loaded
function frameLoaded() {
var iframe = document.getElementById('purchaseIframe');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
purchaseTitle = innerDoc.getElementById('listingTitle');
purchaseNumber = innerDoc.getElementById('auctionSoldIdDisplay');
}
//Checks to see if a purchase number has been selected
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
}
//Converting the value in the title to readable text
purchaseTitle = purchaseTitle.innerHTML;
//Placing the values in to the format I need
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
//Placing the values in to the string to go back in to the email textarea
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
我在这里做错了什么或者使用了错误的事件,因为在我看来,它可能是在iframe完全加载之前尝试抓取值,因此当我生成iframe时出错在同一时间。
请注意我不能使用JQuery
答案 0 :(得分:0)
window.onload = function()是你的答案。
请注意,在下面的示例中,document.getElementById('mydiv')的第一个实例返回null,因为页面(DOM)尚未加载,因此div也不是。
第二个实例是在windows.onload上触发的,这意味着所有页面内容都存在,因此可以找到。
<script type='text/javascript'>
console.log("Page not ready:" + document.getElementById('mydiv'));
window.onload = function() {
console.log("Page ready:" + document.getElementById('mydiv'));
}
</script>
<div id="mydiv">
</div>