简体   繁体   中英

javascript: target div in <a href …>

I have 2 htm files: a.htm and b.htm. In b.htm I have 2 divs, in one is a link to a.htm which I would like to open in second div but it opens as new page in new tab. I'm not good in javascript but I looked many examples so I believe I'm very close to solution but obviously have some error somewhere. Please help!

So, in a.htm I have this:

<html>
    <body>
        TEST
    </body>
</html>

In b.htm I have this:

<html>
    <head>
        <script language="JavaScript">
            function url2div(url,target){
                document.getElementById(target).innerHTML = '<iframe style="width:100%;height:100%;" frameborder="0" src="' + url + '" />';
            }   
        </script>
    </head>
    <body>

        <div id="menu" style="background-color:#FFD700;height:100px;width:100px;float:left;">
            <a href="a.htm" onclick="url2div(this.href,'content')">Click</a>
        </div>

        <div id="content" style="background-color:#EEEEEE;height:100px;width:400px;float:left;">
            Original content
        </div>

    </body>
</html>

Store your link inside the function instead of the href attribute:

<a href="#" onclick="url2div('http://www.bing.com', this)">Click</a>

Change JS to this:

function url2div(url, element) {
    var iframe = document.createElement('iframe');
    iframe.setAttribute('src', url);
    element.appendChild(iframe);
}

JSFiddle Demo #1

if you want to open the link in the same iframe , store the link in any other property other than href . Then, use your current function and it should work fine!

<a href="#" id="a.htm" onclick="url2div(this.id,'content')">Click</a>

JSFiddle Demo #2

I think this isn't as complicated as you're making it. Also, the previous answer isn't quite doing what the OP is asking...so here's my stab at it:

First, I assume html5, so you don't need the "javascript" as part of your script tags. Secondly, I don't think you need to pass around all those variables. Your anchor tag should reference

 <a href=b.htm#content onclick="url2div();"<\a> 

and your javascript should be

  otherPageText = "<iframe src=\"HtmlPage2.html\" width=\"200\" height=\"200\"></iframe>";
  document.getElementById("content").innerHTML = otherPageText;

After that, if you need variables, carefully try to pass them in one at a time.

Part of the original problem is that you're passing "this" which references the new page, not the old one, but by the time that happens you're on the new page and not bringing over the one you want back to the first page. Part of why I stayed away from it.

PS Sorry for the bad formatting. This is all very new to me...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM