<html>
<head>
<meta http-equiv="contentType" content="text/html;charset=gbk">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script>
$(function(){
$("#phone").change(function(){
$("#message").text("正在加载..");
$("#theone").attr("src",$(this).val());
});
$("#theone").load(function(){
$("#message").text("");
});
});
</script>
</head>
<body>
<select id="phone">
<option value="http://www.google.com.hk/">any one</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153427683.jpg">htc dream</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153454306.jpg">htc magic</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153453524.jpg">htc hero</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153464400.jpg">htc hattoo</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153483133.jpg">nexus one</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153485258.jpg">htc legend</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153510582.jpg">htc desire</option>
<option value="http://www.streamcave.com/upload/2010/8/201008251153532800.jpg">motorola milestone</option>
</select>
<span id="message" style="color:green"></span>
<hr/>
<iframe id="theone" src="" width="600" height="700"></iframe>
</body>
</html>
方法二:使用JS
一般来说,我们判断 iframe 是否加载完成其实与 判断 JavaScript 文件是否加载完成 采用的方法很类似:
var iframe = document.createElement("iframe");
iframe.src = "http://www.webjx.com";
if (!/*@cc_on!@*/0) { //if not IE
iframe.onload = function(){
alert("Local iframe is now loaded.");
};} else {
iframe.onreadystatechange = function(){
if (iframe.readyState == "complete"){
alert("Local iframe is now loaded.");
}
};}document.body.appendChild(iframe);
最近, Nicholas C. Zakas 文章《Iframes, onload, and document.domain》的评论中 Christopher 提供了一个新的判断方法(很完美):
var iframe = document.createElement("iframe");
iframe.src = "http://www.webjx.com";
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
alert("Local iframe is now loaded.");
});} else {
iframe.onload = function(){
alert("Local iframe is now loaded.");
};
}
document.body.appendChild(iframe);
几点补充说明:
IE 支持 iframe 的 onload 事件,不过是隐形的,需要通过 attachEvent 来注册。
第二种方法比第一种方法更完美,因为 readystatechange 事件相对于 load 事件有一些潜在的问题。