2014-04-25 47 views
5

我对JavaScript非常陌生,所以请耐心等待。JS document.getElementById在Button上执行点击

我有以下代码:

<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。

截至目前,当网页加载完毕后,它会自动执行并转到网址。

回答

3
<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> 
+0

Yesssss !这工作!非常感谢! – user3573194

+0

这里有一个来自我的“**代码转储”**,我非常感谢您的回答,但这不会帮助任何人解决根本问题,如果您更好地回答了问题,我很乐意更改我的投票,解释什么和为什么这个作品。 – iConnor

+0

你答案中的代码是错误的。您必须删除onclick属性中的括号以使其正常工作 – Luketep

3

您需要将代码包装在一个函数中,然后根据事件调用该函数。这里是按钮的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 example

3

注意,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> 
+1

为什么downvote? – j08691

+0

@ j08691 - 这是一个可怕的答案,我也会低估它。什么工具,使用addEventListener时,有一个onclick属性! – adeneo

+1

我需要一条毛巾来吸收滴水的讽刺。 – j08691

4
  1. 你有两个输入字段用相同的ID,这是一个不行! 改变第二个到不同的东西!

  2. 把你当前的JavaScript代码插入函数

    function clickHandler(event) { 
        // Your code... 
    } 
    
  3. 附加一个事件监听器,您的容器

    var myContainer; 
    
    // assign element from DOM 
    myContainer = document.getElementById(ID_OF_CONTAINER); 
    
    // attach event handler 
    myContainer.addEventListener('click', clickHandler); 
    

这应该做的伎俩

1
<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>