我在我的应用程序中插入了一些显示/隐藏按钮。 我的问题是:当我点击任何按钮时,总是首先打开。 这就是函数:
function showHide(shID) {
if (document.getElementById(shID)) {
if (document.getElementById(shID+'-show').style.display != 'none') {
document.getElementById(shID+'-show').style.display = 'none';
document.getElementById(shID).style.display = 'block';
}
else {
document.getElementById(shID+'-show').style.display = 'inline';
document.getElementById(shID).style.display = 'none';
}
}
}
这是我的插入函数:
function insert($string)
{
$result = '<div id="wrap">
<a href="#" id="example-show" class="showLink" onclick="showHide(\'example\');return false;">Vizualizare</a></p>
<div id="example" class="more">
<p> '. $string .'</p>
<p><a href="#" id="example-hide" class="hideLink" onclick="showHide(\'example\');return false;">Ascunde</a></p>
</div>
</div>';
return $result;
}
最佳答案
您始终向 showHide() 提供相同的参数,因此元素的 ID 将始终相同。但 ID 必须是唯一的。
不使用 ID 从单击的按钮开始遍历文档。
例子:
function showHide(btn)
{
var target;
if(btn.parentNode.parentNode.className=='more')
{
target=btn.parentNode.parentNode;
}
else
{
target=btn.parentNode.getElementsByTagName('div')[0];
}
target.style.display=(target.style.display == 'block')?'none':'block';
target.parentNode.getElementsByTagName('a')[0].style.display
=(target.style.display != 'none')?'none':'block';
}
此处仅提供 this
(不带引号)作为 showHide()
的参数
观看 fiddle :http://jsfiddle.net/doktormolle/kZDvh/
关于javascript - 显示/隐藏按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6490297/