我的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;
}
}
感谢您的回复。
答案 0 :(得分:2)
您必须提供要显示/隐藏您可以覆盖的ID的<p>
,然后使用getElementById
。 ID应作为参数传递给函数。
答案 1 :(得分: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>
标记,您也可以更改此内容以专门查找公开课程