2

私のJSには少し問題があります。同じonclickを持つリンクがいくつかあります。私の問題は、リンクをクリックしたとき、最初のonclick表示です。

私のHTML

<li>
    <a href="#" onclick="openRookie();" class="rookie">John Doe</a>
    <p class="open">
        <a href="#">Portfolio</a>
        <a href="#">Twitter</a>
        <a href="#">Dribbble</a>
    </p>
</li>
<li>
    <a href="#" onclick="openRookie();" class="rookie">John Doe</a>
    <p class="open">
        <a href="#">Portfolio</a>
        <a href="#">Twitter</a>
        <a href="#">Dribbble</a>
    </p>
</li>
<li>
    <a href="#" onclick="openRookie();" class="rookie">John Doe</a>
    <p class="open">
        <a href="#">Portfolio</a>
        <a href="#">Twitter</a>
        <a href="#">Dribbble</a>
    </p>
</li>

私のJS

var s = document.getElementsByClassName('open');
function openRookie() {
    for(var i=0; i<s.length; i++) {
        if (s[i].style.maxHeight !== "20px") {
            s[i].style.maxHeight = "20px";
            s[i].style.marginTop = "10px";
        } else {
            s[i].style.maxHeight = "0";
            s[i].style.marginTop = "0";
        }
        return false;
    }
}

ご回答ありがとうございます。

4

2 に答える 2

2

表示/非表示にする ID に、アクセスして代わり<p>に使用できる ID を指定する必要があります。getElementByIdID はパラメーターとして関数に渡す必要があります。

于 2013-03-29T10:30:05.307 に答える
1

イベントをトリガーした要素をターゲットにすることで、同じ関数を再利用できます。次に、この要素を使用して、イベントに関係するさまざまな html ノードを取得できます。

たとえば、これを参照してくださいhttp://jsfiddle.net/65Xxw/1/

function openRookie(){

    // get the anchor which has been clicked.
    var elm = event.target;
    // get the parent node which is the li tag
    var parent = elm.parentNode;
    // get the child of the li tag which is a paragraph. 
    var paragraphs = parent.getElementsByTagName('p');

    // paragraphs is an array. we know there is only one so can just show.
    paragraphs[0].style.display = "block";

    // prevent the link from doing it's natural thing.
    return false;

}

<p>内に複数のタグがある場合は、これを変更して特にオープン クラスを探すこともできます。<li>

于 2013-03-29T10:48:36.967 に答える