简体   繁体   中英

Passing a variable from <script> to HTML code?

I would like to pass a variable declared between <script> TAGs to the URL in a iframe TAG, like this:

<script>
   var1 = 1;
</script>

<iframe src="http://link_to_site?param=var1>

But this does not work. Is it possible to do it and how should i do ?

Thanks

First you would need a way to identify the target element in your JavaScript code. For example, give the element an id attribute:

<iframe id="myIframe" />

(There are certainly other ways to identify an element. Fairly complex queries can be constructed to identify specific elements throughout the DOM. But an id is a particularly straightforward approach at least for this example.)

Then in your JavaScript code you'd get a reference to that element and set its src property:

var var1 = 1;
document.getElementById('myIframe').src = 'http://link_to_site?param=' + var1;

One thing to note is that this code would need to execute after that element exists on the page. If it runs above that element on the page then that element won't yet exist and getElementById() would return nothing.

"After" could mean that it runs immediately but exists "lower" on the page than the element. Or it could mean that the code is placed anywhere on the page but doesn't actually execute until a later time, such as in an event handler.

*FYI- Sorry, but the accepted answer doesn't actually work. Read below. *

I suggest that you use the jQuery JS library to assist in your task. It normalizes the JS environment so you don't have to worry about what browser your user is using.

It also makes it easier to do some simple tasks like getting specific elements etc.

Here is code that shows how to dynamically create an iFrame AFTER the page has finished loading. This is important because JS runs synchronously: in other words, if you write JS for a specific element, but that element doesn't yet exist on the page, the JS will fail.

By wrapping your code in:

$(document).ready(function(){})

you ensure that the page will finishing loading BEFORE your JS executes.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>

<body>

</body>

<script type="text/javascript">
    var1 = 1;
    $(document).ready(function(){
        var theiFrame = '<iframe src="http://link_to_site?param=' + var1 + '">';
        $('body').append(theiFrame);    
    })
</script>

iFrames are a little weird in that they mess with the "onload" event of the document. That's another reason to dynamically add your iFrame to the DOM instead of adding it as an HTML tag. Read this article for more info:

http://www.aaronpeters.nl/blog/iframe-loading-techniques-performance

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