我有两个工作按钮,我想合并到一个按钮,切换现有按钮的功能和文本。现有按钮是:
<button type="button"
onclick="document.getElementById('layer3').style.opacity = '0'">
HIDE SHAPE</button>
<button type="button"
onclick="document.getElementById('layer3').style.opacity = '100'">
SHOW SHAPE</button>
&#13;
到目前为止,我已经能够使用javascript进行文本更改,但我无法弄清楚如何正确调用和切换函数。这就是我所拥有的:
// i'm trying to call two functions (toggleName and shapeOpacity here)
document.getElementById('ShapeButton').onclick = function(){
toggleName(this, 'Hide Shape', "Show Shape"); shapeOpacity();
};
// the toggle name function (working)
function toggleName(el, message1, message2) {
if (!el || !message1 || !message2) {
return false;
}
var text = el.tagName.toLowerCase() == 'input' ? el.value : (el.textContent || el.innerText),
newText = text == message1 ? message2 : message1;
if (el.tagName.toLowerCase() == 'input') {
el.value = newText;
}
else {
el.firstChild.nodeValue = newText;
}
}
// the second click function (not working)
function shapeOpacity() {
if ( action == 1 ) {
$document.getElementById('layer3').style.opacity = '0';
action = 2;
} else {
document.getElementById('layer3').style.opacity = '100';
action = 1;
}
}
&#13;
<input type=button value="Hide Shape" id= "ShapeButton" />
&#13;
我确定我错过了一些非常基本的东西。非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
我发现以下代码运行正常。请检查您是否为 layer3 正确设置了ID。还要检查您是否已声明操作 var。
使用jQuery时,有更好的方法可以做到这一点。但目前您可以尝试以下代码。
<!DOCTYPE HTML>
<html>
<head>
<title>Event Scheduler</title>
</head>
<body>
<form name= "evtForm" method="post" onsubmit="Validate()">
<input type=button value="Hide Shape" id= "ShapeButton" />
<div id='layer3'> This is your layer 3 I guess</div>
</form>
<script>
var action = 1; //make sure you declare this
document.getElementById('ShapeButton').onclick = function(){
toggleName(this, 'Hide Shape', "Show Shape"); shapeOpacity();
};
// the toggle name function (working)
function toggleName(el, message1, message2) {
if (!el || !message1 || !message2) {
return false;
}
var text = el.tagName.toLowerCase() == 'input' ? el.value : (el.textContent || el.innerText),
newText = text == message1 ? message2 : message1;
if (el.tagName.toLowerCase() == 'input') {
el.value = newText;
}
else {
el.firstChild.nodeValue = newText;
}
}
function shapeOpacity() {
if ( action == 1 ) {
document.getElementById('layer3').style.opacity = '0';
action = 2;
} else {
document.getElementById('layer3').style.opacity = '100';
action = 1;
}
}
</script>
</body>
</html>