JavaScript document.getElementById 在按钮点击时执行

5

我对JavaScript非常陌生,请理解。

我有以下代码:

<input id="test" name="test" type="text" value="" /> 
<input id="test" type="button" value="Go!" /> 
<script type="text/javascript">
    window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
</script>

我希望代码只有在按钮点击时才会执行。该函数的作用是将用户输入数据添加到URL的末尾,然后在按钮点击时加载该URL。
目前,在加载页面时,它会自动执行并转到URL。
5个回答

5
  1. You have two input fields with the same ID, that's a no go! Change the second one to something different!

  2. Put your current javascript code into a function

    function clickHandler(event) {
        // Your code...
    }
    
  3. Attach an event listener to your container

    var myContainer;
    
    // assign element from DOM
    myContainer = document.getElementById(ID_OF_CONTAINER);
    
    // attach event handler
    myContainer.addEventListener('click', clickHandler);
    
那应该就可以了。

4
<input id="test" name="test" type="text" value="" /> 
<input id="test2" type="button" onclick="fnc()" value="Go!" /> 
<script type="text/javascript">
function fnc(){
window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
}

</script>

这里是我给你的“代码转储”的负一分,感谢你的回答尝试,但这并没有帮助任何人解决根本问题。如果你能改进你的回答并解释它的原理和作用,我很乐意改变我的投票。 - iConnor
你的答案中的代码是错误的。你必须删除onclick属性中的括号才能使其正常工作。 - Luketep

4

你需要将代码包裹在一个函数中,然后基于事件来调用该函数。这里使用了按钮的onclick事件。注意,ID必须是唯一的。将你的代码更改为:

<input id="test" name="test" type="text" value="" /> 
<input id="test2" type="button" value="Go!" onclick="foo()" /> 
<script type="text/javascript">
function foo(){
    window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
}
</script>

jsFiddle示例


4
请注意,ID是唯一的,您需要使用事件监听器来处理它。
<input id="test" name="test" type="text" value="" /> 
<input id="button" type="button" value="Go!" /> 

<script type="text/javascript">
    document.getElementById('button').addEventListener('click', function() {
        var val = document.getElementById('test').value;
        window.location.href="http://www.thenewendurancefitness.com/" + val;
    }, false):

</script>

@j08691 - 这是一个可怕的回答,我也会给它点个踩。使用addEventListener,而当有onclick属性可用时,这太幼稚了! - adeneo
1
我需要一条毛巾来擦拭滴落的讽刺。 - j08691
想要捧腹大笑吗?看看 Connor 对我的回答发表的评论吧。 - j08691

2
<form onsubmit="return submit()">
    <input id="test" name="test" type="text" value="" /> 
    <input id="submit" type="submit" value="Go!" />
</form>
<script type="text/javascript">
function submit() {
    location.href="http://www.thenewendurancefitness.com/"+document.getElementById('test').value;
}
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接