开发者

How to change iframe src from another page

开发者 https://www.devze.com 2023-03-31 15:51 出处:网络
I have a php page that includes another php page named \'tree.php\' and also contain an iframe .The Iframe calls the page \'contentpage.php\'.Then i want to change the src of iframe using javascript o

I have a php page that includes another php page named 'tree.php' and also contain an iframe .The Iframe calls the page 'contentpage.php'.Then i want to change the src of iframe using javascript or jquery from tree.php.I have alredy tried these

document.getElementById['contentframe'].src 开发者_StackOverflow中文版= "contentpage.php";
$("#contentframe").attr("src", "contentpage.php");


Assuming all the frames are in the same domain, this can be done easily.

<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
         var change_iframe_src = function(new_src) {
             $("#myframe-content").attr('src', new_src);
         }
    </script>
</head>

<body>
    <!-- frame which includes your tree.php -->
    <iframe src="iframe.html" width="200" height="200" border="1"></iframe>
    <!-- frame for which we will change src attribute -->
    <iframe id="myframe-content" src="" width="400" height="200" border="1"></iframe>        
</body>

Now in tree.php attach a click handler for something that should change the src of the iframe attribute (possibly some link). Example:

<html>
<head>
    <title>Tree</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#nav a").click(function(e) {
                e.preventDefault();
                // call function in a parent frame
                parent.window.change_iframe_src(this.rel);
            })
        })
    </script>
</head>
<body>
    <div id="nav">
        <a href="#" rel="iframe2.html">Change iframe src to iframe2.html</a>
        <a href="#" rel="iframe3.html">Change iframe src to iframe3.html</a>
    </div>
</body>

Now with this kind of setup the links in the tree.php would call the function defined in parent window (the window which embeded the tree.php itself). That function (change_iframe_src in this example) takes one argument which is a new url to which src attribute of the frame myframe-content should be changed to.

Again, this works as long as the base document and the iframe with tree.php are documents in the same domain.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号