0

我有一个处理按键的 main.js。我有一个 index.html,我想从 main.js 接收一些变量并做出决定。例如,我想将一个 url 从 main.js 发送到 index.html .. 我在 main.js 中尝试了这段代码,但没有成功。

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

在我的 index.html 中,我有:

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

我只想从 main.js 设置我的 url 输入对象的值。有什么帮助吗?

4

3 回答 3

0

您何时调用值分配很重要。它必须在 DOM 加载之后。为此,您可以尝试以下方法之一。

  1. 最简单的方法是将您的 main.js 脚本标签放在/body关闭标签之后。它应该工作。

  2. 在 main.js 中的函数中分配值并调用该函数onload事件。

--main.js

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

--index.html

<body onload="assignValue()" >
于 2012-08-16T10:21:13.017 回答
0

您的代码对我来说看起来不错,但触发它的代码可能没有被触发。您尚未包含触发 URL 设置的代码的其他部分。

于 2012-08-16T10:21:31.037 回答
0

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

于 2012-08-16T10:23:55.870 回答