如何将此代码压缩为一个块

时间:2015-03-16 03:46:14

标签: javascript html

我想将所有这些代码压缩成一个块而不是5个。它工作得很完美,但它非常臃肿。任何其他改进此代码的技巧都将不胜感激。

JS:

function vanish1() {
    var el = document.getElementById('priceCheck1');
    if (el.style.display == "block") {
        el.style.display = "none";
    } else {
        el.style.display = "block";
    }
}

function vanish2() {
    var el = document.getElementById('priceCheck2');
    if (el.style.display == "block") {
        el.style.display = "none";
    } else {
        el.style.display = "block";
    }
}

function vanish3() {
    var el = document.getElementById('priceCheck3');
    if (el.style.display == "block") {
        el.style.display = "none";
    } else {
        el.style.display = "block";
    }
}

HTML:

<div id="priceCheck1">
test1
    </div>
    <div id="priceCheck2">   
test2
    </div>    
    <div id="priceCheck3">
test3
    </div>

3 个答案:

答案 0 :(得分:1)

你可以这样做:

function vanish(elementName) {
    var el = document.getElementById(elementName);
    if (el.style.display == "block") el.style.display = "none";
    else el.style.display = "block";
}

函数调用:

vanish('priceCheck1');

答案 1 :(得分:0)

您好,您可以为HTML添加类名。 然后你可以通过classname获取每个HTML ..

答案 2 :(得分:0)

更小......

function vanish(style) {
    style.display == "block" ? style.display = "none" : style.display = "block";
}

vanish(document.getElementById("priceCheck1").style);

function vanish(element) {
    element.style.display == "block" ? element.style.display = "none" : element.style.display = "block";
}

vanish(document.getElementById("priceCheck1"));