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

你必须给<p>你想要显示/隐藏的 id 一个你可以到达然后使用的 id getElementById。ID 应作为参数传递给函数。

于 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 回答