Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
778 views
in Technique[技术] by (71.8m points)

changing iframe source with jquery

I've been trying this for a bit now and have looked at other answers to similar questions on SO, but when I am trying to change the src attribute of an iframe, it updates it for the whole window. Here is the following code I am using that works correctly (no jquery):

<html>
<head>
<style type="text/css">
iframe#ifrm { 
    border:none;
    padding:.5em;
    margin:1.5em 0 1em;
    width:100%;
    height:100%;
}
</style>
<script src="./js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
// <![CDATA[
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // this is the function I'm trying to replace:
    function loadIframe(iframeName, url) {
    if ( window.frames[iframeName] ) {
        window.frames[iframeName].location = url;   
        return false;
    }
    return true;
}
// ]]>
</script>
</head>

<body>
<ul>
<li><a href="http://www.google.com/" onclick="return loadIframe('ifrm', this.href)">Page 1</a> </li>
<li><a href="tabs.html" onclick="return loadIframe('ifrm', this.href)">Page 2</a></li>
</ul>
<div class="iframe">
<iframe name="ifrm" id="ifrm" src="tabs.html" frameborder="0">
Your browser doesn't support iframes.</iframe>

As I said, I've tried

$('#ifrm').attr('src', "http://www.google.com")

which displays the page, but not in the iframe. I'm really just learning jquery, but I can't figure out what's different about my situation than other similar questions like this:

Jquery and iFrame update

Thanks.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...