所以我在我的 Js 中有这个函数,它在链接 onclick() 事件上被调用。
这是 HTML:
<li class="collapsed">
<span>
<a href="#!" onclick="expand(this)">Directions</a>
</span>
<p>ajajgajajys agajgjgtajgtdja ajdtajtjate ajgdjagjd ajt</p>
</li>
这是 Javascript:
function expand(myElem)
{
if (myElem.parentNode.parentNode.style.height<100)
myElem.parentNode.parentNode.style.height="100px";
else
myElem.parentNode.parentNode.style.height="45px";
}
很明显,代码扩展了链接所在的 li 父标签。最初,li 标签在 CSS 中设置为 height:45px;
。然后它们变为 100px
并返回。
我遇到的问题是 javascript 只能工作两次。
我可以单击 oncde 的链接并展开 li 的链接。然后我可以点击它们并折叠 li 的。然后它不想再工作了。
我正在查看我的浏览器错误,我发现了这个:
"Error parsing value for 'height'. Declaration dropped.
在网上查了很多之后,我认为这可能是因为我没有在我的 js 中包含单元声明。但我是!
myElem.parentNode.parentNode.style.height="45px"; ---- as you can see.
****备注:我的解决方案* ****
对于任何偶然发现此线程的人来说,这是我的解决方案:
HTML --> 我结束了一些类似的事情:
<span class="heading">
Link1
<span>
<span class="information">
Info about Link1
</span>
<span class="heading">
Link2
<span>
<span class="information">
Info about Link2
</span>
而且 Jquery 非常简单:
$(document).ready(function() {
$(".information").hide();
$(".heading").click(function(){
var item = $(this);
item.next().slideToggle(500);
});
});
... super 简单,很有魅力
最佳答案
尝试使用 replace
和 parseInt
函数,例如,
function expand(myElem)
{
if (parseInt(myElem.parentNode.parentNode.style.height.replace('px','')) < 100)
myElem.parentNode.parentNode.style.height="100px";
else
myElem.parentNode.parentNode.style.height="45px";
}
您可以使用 Jquery 来简化它,例如,
HTML
<li class="collapsed">
<span>
<a href="#!" class="direction">Directions</a>
</span>
<p>ajajgajajys agajgjgtajgtdja ajdtajtjate ajgdjagjd ajt</p>
</li>
脚本
$(function(){
$('.direction').on('click',function(e){
var ht= $('.collapsed').height()==100 ? 45 : 100;
$('.collapsed').height(ht);
});
});
关于javascript不想解析文本超过两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17961398/