0

我从 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

4 回答 4

2

您的代码有一些问题。

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

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

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

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

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

第四,您的函数查找具有 id 的元素,该元素one不存在。你的意思是 idnothing吗?

第五,假设你使用正确的 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 学习网站。

于 2012-07-10T14:54:12.407 回答
0

将您的输入更改为此

<input type=button value="Button?" onclick="take();" />
于 2012-07-10T14:46:58.217 回答
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 ,并且没有带有 id 的元素。所以改成
document.getElementById("one")onenothing

于 2012-07-10T14:47:15.180 回答
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;
于 2012-07-10T14:55:45.100 回答