[英]Get innerHTML after the page loads completely
I'm attempting a make random quote machine with a tweet button to tweet the quote. 我正在尝试使用推文按钮制作随机报价机器来推文。 The random quote is coming up just fine.
随机报价即将到来。 The code..
编码..
var forismaticAPI = 'http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?';
$(document).ready(function() {
var template = function(data) {
$('#quotearea').empty();
$('#quotearea').append('<blockquote id="quote">' + data.quoteText + '</blockquote>' + '<p id="author"> — ' + data.quoteAuthor + '</p>');
$('#quotearea').show();
};
var dataAppend = function() {
$.getJSON(forismaticAPI, template);
};
}
My next task is to get the quote content to be tweeted. 我的下一个任务是获取推文内容。 So once the window loads completely i want to get the innerHTML of
#quote
which contains the quote. 因此,一旦窗口完全加载,我想获得包含引用的
#quote
的innerHTML。 So i write a window.onload function like this.. 所以我写了一个这样的window.onload函数..
window.onload = function(){
var quote = document.getElementById('quote');
console.log(quote.innerHTML);
}
But I'm getting an error Uncaught TypeError: Cannot read property 'innerHTML' of null(…)
.. Since there is small delay in loading the quote, the window load function returns a null. 但是我得到一个错误
Uncaught TypeError: Cannot read property 'innerHTML' of null(…)
。由于加载引号有小的延迟,窗口加载函数返回null。 How to get the innerHTML of a div only when the content is loaded and ready? 如何在内容加载和准备好的时候获取div的innerHTML?
Your #quote
element is created after the window.onload
event, because it's only created on the return of your ajax call. 你的
#quote
元素是在window.onload
事件之后创建的,因为它只在你的ajax调用返回时创建。 Move the code from onload
to success
of the ajax call, as BlueBoy suggested in comments. 正如BlueBoy在评论中建议的那样,将代码从
onload
移动到ajax调用的success
。 In your case, the success function is the one you named template
. 在您的情况下,成功函数是您命名
template
函数。
You can access your element immediately after creating it: 您可以在创建元素后立即访问它:
var template = function(data) {
$('#quotearea').empty();
$('#quotearea').append('<blockquote id="quote">' + data.quoteText
+ '</blockquote>' + '<p id="author"> — ' + data.quoteAuthor + '</p>');
$('#quotearea').show();
console.log(document.getElementById('quote'));
};
You can't call the innerHTML
method on DOM elements that do not exist yet. 您不能在尚不存在的DOM元素上调用
innerHTML
方法。 So the first moment you can run your function is after the append()
call, which is creating a DOM element with and id
of quote
. 所以你可以运行你的函数的第一刻是在
append()
调用之后,它正在创建一个带有id
和quote
的DOM元素。
Without testing it, my guess is that onload is firing before the document ready. 没有测试它,我的猜测是onload在文档准备好之前触发。 So you may want to 1) set a flag when the content has been written, Then 2) check in the second function, if null schedule it to run again in 100 ms using setTimeout().
所以你可能想要1)在写入内容时设置一个标志,然后2)检查第二个函数,如果为null,则使用setTimeout()在100毫秒内再次运行它。
使用html函数?
var code = $('#quotearea').html();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.