jQuery的功能有时不运行
问题描述:
我有以下的功能,基本上使用的iframe的高度设置为高度它的内容:jQuery的功能有时不运行
$("#MSOPageViewerWebPart_WebPartWPQ1").load(function()
{
var Height = document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').contentWindow.document.body.scrollHeight;
document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').height = Height;
});
绝大多数的时间预计将运行,但在奇怪的情况下,它会在它工作之前多次重新加载页面。当然,试图调试它是没有用的,因为它似乎总是碰到功能和工作。
任何人都知道为什么它不可能每次都工作?
答
试试这个:
$(function(){
$("#MSOPageViewerWebPart_WebPartWPQ1").load(function()
{
setTimeout(function(){
var Height = document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').contentWindow.document.body.scrollHeight;
document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').height = Height;
});
},100);
});
答
为什么使用 '的getElementById'。尝试使用jQuery内建的选择器机制:
jQuery("#MSOPageViewerWebPart_WebPartWPQ1").load(function() {
// not sure, if this row work's fine in every context, try: http://stackoverflow.com/questions/926916/how-to-get-the-bodys-content-of-an-iframe-in-javascript/11107977#11107977
var scrollHeight = jQuery(this).contentWindow.document.body.scrollHeight;
jQuery(this).height = scrollHeight;
});
答
我遇到了同样的问题。有时候没有脚本运行。但是,我认为这是一个连接问题。当我没有连接到互联网,并查看我的网站(浏览器使用其文件路径,例如file:/// C:/Users/Alejandro/Dropbox/Prices/index.html)时,页面需要相当长的时间加载时间(这很奇怪,因为它是轻量级的),之后显示内容但没有任何脚本运行。
我想它在加载页面时会延迟,因为浏览器试图下载jQuery源代码。
所以,我会做的是包括一个jquery后备。 More info in xandercoded's answer。
虽然如果你设置你的网站在线,这将是愚蠢的,因为用户已经需要互联网连接下载你的网站(从而jQuery将被下载)。
这是否发生在所有浏览器上? – Andre 2011-04-27 16:13:12
只在IE8上测试,因为这是所有用户都会使用的。还有一些SharePoint的“细微差别”,我们决定专注于IE。 – anothershrubery 2011-04-27 16:13:52
你试图把它放在$(function {})? – alexl 2011-04-27 16:15:20