简体   繁体   English

从外部.js文件在.html文件中设置值

[英]set a value in .html file from an external .js file

i have a main.js that handles Key pressed. 我有一个main.js来处理按下的键。 and i have a index.html that i want to recieve some variables from main.js and make decisions about it. 我有一个index.html我想从main.js接收一些变量并做出决定。 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. 例如,我想从main.js发送一个URL到index.html ..我在main.js中尝试了此代码,但是没有用。

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

in my index.html i have: 在我的index.html中,我有:

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

i just want to set value of my url input object from main.js. 我只想从main.js设置我的url输入对象的值。 any help? 有什么帮助吗?

It is important when did you call value assignment. 何时调用值分配很重要。 It must be after DOM loaded. 必须在加载DOM之后。 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. 最简单的方法是将main.js脚本标签放在/body close标签之后。 it should work. 它应该工作。

  2. Assign the value in a function in main.js and call that function onload event. 在main.js中的函数中分配值,然后调用该函数的onload事件。

--main.js --main.js

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

--index.html --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. 您尚未包括触发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. 我猜它没有起作用的原因是因为您没有等待DOM初始化并且Web浏览器已经完成了对HTML的解析。

The simplest 'fix' for this problem would be to hook into the window.onload callback in your main.js file: 解决此问题的最简单方法是将其插入main.js文件中的window.onload回调中:

// 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; 但是,最好监听DOM Ready事件。 if you're using jQuery then you can simply write: 如果您使用的是jQuery,则可以简单地编写:

// 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 如果您不想依赖jQuery,那么可以看看超轻量级的DOMReady.js。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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