简体   繁体   中英

set a value in .html file from an external .js file

i have a main.js that handles Key pressed. and i have a index.html that i want to recieve some variables from main.js and make decisions about it. for example i want to send a url from main.js to index.html .. i try this code in my main.js but not worked.

document.getElementById("url").value = "http://example.com";

in my index.html i have:

<form name="Params">
<input id="url" type="hidden" value="">
</form>

i just want to set value of my url input object from main.js. any help?

It is important when did you call value assignment. It must be after DOM loaded. To do this you can try one of the followings.

  1. Easiest way is just place your main.js script tag after /body close tag. it should work.

  2. Assign the value in a function in main.js and call that function onload event.

--main.js

function assignValue()
{
    document.getElementById("url").value = "http://example.com";
}

--index.html

<body onload="assignValue()" >

Your code looks fine to me but perhaps the code that triggers it isn't being fired. You haven't included the other part of your code that triggers the setting of the URL.

I'm guessing the reason it hasn't worked is because you're not waiting for DOM to initialize and the Web Browser has finished parsing the HTML.

The simplest 'fix' for this problem would be to hook into the window.onload callback in your main.js file:

// Wait for the DOM to finish loading.
var previousOnload = window.onload;
window.onload = function () {

    // Execute any other `onload` function which may have been bound previously.
    if (typeof previousOnload === 'function') {
        previousOnload();
    }

    document.getElementById("url").value = "http://example.com";
});

However, it is preferred to listen for the DOM Ready event instead; if you're using jQuery then you can simply write:

// Wait for the DOM to initialize first.
$(function () { 
    document.getElementById("url").value = "http://example.com";    
});

If you don't want to depend on jQuery then you could have a look into the super-lightweight DOMReady.js

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