GDe*_*gns 10 html javascript text function onclick
我正在尝试创建3个按钮,并使用javascript,如果单击按钮1,则将"单击按钮"文本更改为"按下按钮1"
按钮2和3也一样!如果按下按钮3,文本颜色将变为绿色
但是,我似乎无法让它工作!任何帮助,将不胜感激
这是我目前的代码:
<!DOCTYPE html>
<html>
<head>
<title>Button</title>
</head>
<body>
<script type="text/javascript">
function changeText() {
var b1 = document.getElementById('b1');
var b2 = document.getElementById('b2');
var b3 = document.getElementById('b3');
if(b1.onclick="changeText();") {
document.getElementById('pText').innerHTML = "You pressed button 1";
}
if(b2.onlick="changeText();") {
document.getElementById('pText').innerHTML = "You pressed Button 2";
}
}
</script>
<input type="button" value="Button 1" id="b1" onclick="changeText();"/>
<input type="button" value="Button 2" id="b2" onclick="changeText();"/>
<input type="button" value="Button 3" id="b3" onclick="changeText();"/>
<p id="pText">Click on a Button</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
sha*_*e14 13
你可以试试这个:
<!DOCTYPE html>
<html>
<head>
<title>Button</title>
</head>
<body>
<script type="text/javascript">
function changeText(value) {
document.getElementById('pText').innerHTML = "You pressed " + value;
}
</script>
<input type="button" value="Button 1" id="b1" onclick="changeText(this.value);"/>
<input type="button" value="Button 2" id="b2" onclick="changeText(this.value);"/>
<input type="button" value="Button 3" id="b3" onclick="changeText(this.value);"/>
<p id="pText">Click on a Button</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这里你要做的就是每当你点击按钮时,onlick();
调用的函数包含你刚刚点击的按钮元素的值.changeText();
现在要做的所有功能都是编辑要编辑的元素的innerHTML.直.
希望这可以帮助.
更新代码:(反映您更新的参数)
<!DOCTYPE html>
<html>
<head>
<title>Button</title>
</head>
<body>
<script type="text/javascript">
function changeText(value) {
document.getElementById('pText').innerHTML = "You pressed " + value;
if(value == "Button 3")
{
document.getElementById('pText').setAttribute('style', 'color: green');}
}
</script>
<input type="button" value="Button 1" id="b1" onclick="changeText(this.value);"/>
<input type="button" value="Button 2" id="b2" onclick="changeText(this.value);"/>
<input type="button" value="Button 3" id="b3" onclick="changeText(this.value);"/>
<p id="pText">Click on a Button</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
你很接近,但没有雪茄。
为了正确识别您单击的按钮,您应该this
与函数调用一起发送,这样您就可以获得对所单击的对象的引用。在 if 语句中比较onclick
效果不佳,因为它是函数指针,而不是字符串。
尝试类似的方法:
<input type="button" value="Button 1" id="b1" onclick="changeText(this);"/>
Run Code Online (Sandbox Code Playgroud)
你changeText()
现在应该是这样的。您可以使用这个示例,但您必须自己弄清楚其余的内容。不过,这应该为您指明正确的方向。
function changeText(elementClicked) {
var button1 = document.getElementById('b1');
if (elementClicked == button1) {
// button 1 was clicked
}
}
Run Code Online (Sandbox Code Playgroud)