简单的文件无法正常工作

0 html javascript

如果启用了java,我正在编写一个简单的脚本来传递值"... php?answer = 1".我到目前为止......

<script language="text/javascript">
document.form.answer.value=1;
</script>
</head>
<body>
<form name="form" action="enabled_catch.php" method="get">
<input type="hidden" name="answer">
<input type="submit" value="click me">
</form>
Run Code Online (Sandbox Code Playgroud)

...但脚本似乎没有分配answer.value ="1" - 我不知道为什么.你能帮我吗

Dar*_*rov 8

This happens because at the moment you are assigning this value using javascript (do not confuse with Java) the DOM is not loaded yet and the form doesn't exist. Try this instead:

<script type="text/javascript">
window.onload = function() {
    document.form.answer.value = '1';
};
</script>
Run Code Online (Sandbox Code Playgroud)

or better assign an id to your input and use this id:

<head>
<script type="text/javascript">
window.onload = function() {
    document.getElementById('answer').value = '1';
};
</script>
</head>
<body>
    <form name="form" action="enabled_catch.php" method="get">
        <input type="hidden" id="answer" name="answer" />
        <input type="submit" value="click me" />
    </form>
</body>
Run Code Online (Sandbox Code Playgroud)

或者甚至更好地使用jQuery框架这样的jQuery来操作DOM以确保跨浏览器兼容性:

<script type="text/javascript">
$(function() {
    $(':hidden[name=answer]').val('1');
});
</script>
Run Code Online (Sandbox Code Playgroud)