JS函数调用

问题描述:

我从JS开始,一直在遇到我正在编写的特定函数的问题。目的是在按下按钮后更改文本。 “无”文本应该变成“你说你好,我说嘿?”随着嘿?作为文件已经在文件上。JS函数调用

这是代码,任何指针都会受到欢迎!

<html> 
<head> 
<title>Javascript test </title> 
</head> 

<body> 

<p id="hey">Hey?</p> 
<p id ="nothing">Nothing</p> 
<INPUT type =button VALUE="Button?" OnClick=(take())> 

<script> 
function take(){ 
var hey=document.getElementById("hey"); 
var nothing =document.getElementById("one"); 

nothing.appendChild(document.createTextNode("You say hi, I say " + hey)); 
} 
</script> 
</body> 
</html> 

好的,谢谢你们所有的帮助。没有人特别是100%正确,但我尝试了所有建议的组合,并获得了约99%的方式去我想去的地方。我的代码现在看起来像这样。我试图做的最后一项更改不是追加新的文本字符串,而是使用当前追加的字符串替换旧的字符串。

<html> 
<head> 
<title>Javascript test </title> 
</head> 

<body> 

<p id="hey">Hey?</p> 
<p id ="nothing">Nothing</p> 
<input type ="button" value="Button?" OnClick="take();"/> 

<script> 
function take(){ 
var hey=document.getElementById("hey"); 
var nothing =document.getElementById("nothing"); 

nothing.appendChild(document.createTextNode("You say hi, I say " + hey.innerHTML)); 

} 

</script> 
</body> 
</html> 

我欣赏的帮助,谢谢堆栈溢出社区!

+0

所以,你要添加“你说嗨,我说嘿”后一无所获?你为什么得到“嘿”元素? – bokonic 2012-07-10 14:45:26

+1

你可能想看看jQuery。用它做这样的事情更容易。 – woz 2012-07-10 14:48:10

+0

@woz我不认为这值得从jQuery的开销,但这只是我 – jbabey 2012-07-10 14:48:39

你的代码有几个问题。

首先,您应该在脚本标记上指定type="text/javascript"

其次,你的投入应该是这样的:

<input id="button" type="button" value="Button?" /> 

第三,你应该绑定在脚本标签事件处理程序(见SoC):

document.getElementById('button').onclick = take; 

四,您的函数查找一个id为one的元素,它不存在。你的意思是id nothing?第五,假设您使用正确的ID来获取nothing元素,则在设置该值时需要使用其他p中的值。

var take = function() { 
    var hey = document.getElementById('hey'); 
    var nothing = document.getElementById('nothing'); 

    nothing.innerHTML= 'You say hi, I say ' + hey.innerHTML; 
}; 

看到这里工作的例子:http://jsfiddle.net/M5UWn/

作为一个方面说明,我发现jQFundamentals一个很好的学习网站都jQuery和本地JavaScript。

+0

+1比我的回答:) – 2012-07-10 14:58:42

+0

我发现教程类似于HTML和CSS的JQFundamentals,但没有找到一个JS。谢谢一堆! – 2012-07-10 15:10:46

您输入改成这样

<input type=button value="Button?" onclick="take();" /> 

<html> 
<head> 
<title>Javascript test </title> 
</head> 

<body> 

<p id="hey">Hey?</p> 
<p id ="nothing">Nothing</p> 
<input type="button" value="Button?" onClick="take()"/> 

<script> 
function take(){ 
var hey=document.getElementById("hey"); 
var nothing =document.getElementById("nothing"); 

nothing.appendChild(document.createTextNode("You say hi, I say "+hey.value)); 
} 
</script> 
</body> 
</html> 

我已经改变了
输入标签的
加引号输入的类型和的OnClick结束
你在做document.getElementById("one")并没有与元素id one。所以改为nothing

+0

请解释您所做的修复,以便人们无需进行字符串比较即可找到您所做的修改。 – jbabey 2012-07-10 14:47:58

+0

这仍然是无效的HTML,没有关闭输入标签加上它真的应该是小写'输入' – 2012-07-10 14:48:34

+0

完成..我已经提到所有的变化我做了 – 2012-07-10 14:51:52

这里有几个指针:

更改您的按钮输入HTML看起来像这样:

<INPUT type="button" VALUE="Button?" OnClick="take()"> 

请注意,所有的属性都是在双引号。另外,函数调用的附加括号被删除。

当你得到'没有'元素时,你使用了错误的ID。它应该是这样的:

var nothing = document.getElementById("nothing"); 

要更改文本,它更简单,只需使用此代码:

nothing.innerText = "You say hi, I say " + hey.innerText;