更改显示/隐藏文本并最初显示

时间:2018-07-27 18:36:14

标签: javascript

我有这样的代码,效果很好:而且我不想对它使用jquery,因为jquery对于这种小功能有点过分了

function showHide(targetName) {
    if( document.getElementById ) { // NS6+
        target = document.getElementById(targetName);
    } else if( document.all ) { // IE4+
        target = document.all[targetName];
    }

    if( target ) {
        if( target.style.display == "none" ) {
            target.style.display = "inline";

        } else {
            target.style.display = "none";
        }
    }
}

<a href="javascript:showHide('stackbox')">Stack Trace (click to expand)</a>

我想将其行为最初更改为show和label,显示为:

<a href="javascript:showHide('stackbox')">Stack Trace (click to collapse)</a>

2 个答案:

答案 0 :(得分:0)

您可以根据是否隐藏textContent来更改链接的#stackbox

<a href="javascript:showHide('stackbox')" id="link">Stack Trace (click to collapse)</a>
<p/>
<span id="stackbox">Stack trace...</span>
<script>
function showHide(targetName) {
var elem = document.getElementById("link");
    if( document.getElementById ) { // NS6+
        target = document.getElementById(targetName);
    } else if( document.all ) { // IE4+
        target = document.all[targetName];
    }

    if( target ) {
        if( target.style.display == "none" ) {
            target.style.display = "inline";
            elem.textContent = "Stack Trace (click to collapse)"

        } else {
            target.style.display = "none";
            elem.textContent = "Stack Trace (click to expand)";
        }
    }
}
</script>

答案 1 :(得分:0)

使用“ target.innerText”作为波纹管:

    if( target ) {
    if( target.style.display == "none" ) {
        target.style.display = "inline";
        target.innerText = "Stack Trace (click to collapse)";
    } else {
        target.style.display = "none";
        target.innerText = "Stack Trace (click to expand)";
    }
}