JS函数调用

时间:2012-07-10 14:43:57

标签: javascript

我开始使用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>

我感谢您的帮助,谢谢Stack Overflow社区!

4 个答案:

答案 0 :(得分:2)

您的代码存在一些问题。

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

其次,您的输入应如下所示:

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

第三,您应该在脚本标记中绑定您的事件处理程序(请参阅SoC):

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

第四,您的函数会查找ID为one的元素,该元素不存在。您的意思是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的优秀学习网站。

答案 1 :(得分:0)

将您的输入更改为此

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

答案 2 :(得分:0)

<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")并且没有标识为one的元素。所以改为nothing

答案 3 :(得分:0)

这里有几点指示:

将按钮输入html更改为:

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

请注意,所有属性都是双引号。此外,函数调用周围的额外括号将被删除。

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

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

要更改文本,只需使用此代码即可:

nothing.innerText = "You say hi, I say " + hey.innerText;
相关问题