我有以下 Javascript 函数用于展开折叠内容:
function showAns(inp){
var hide="#hideAns"+inp;
var show="#showAns"+inp;
var ansdiv ="#ans"+inp;
$(hide).click(function(){
$(ansdiv).hide(500);
$(hide).hide();
$(show).show();
});
$(show).click(function(){
$(ansdiv).show(500);
$(hide).show();
$(show).hide();
});
}
此函数是从以下生成的 HTML 代码中调用的:
<div class="qbox">
<span class="qclass">Q. No.1) This is test question 112
<img id ="showAns1" class="icons" src="img/expand.png" onclick="javascript:showAns(1)" alt="show" width="20" height="20" style="float:right; cursor:pointer;">
<img id="hideAns1" class="icons" src="img/collapse.png" onclick="javascript:showAns(1)" alt="hide" width="20" height="20" style="float:right; display:none; cursor:pointer;">
</span>
<img alt="image" class="img" src="img/sample.jpg">
<hr />
<span id="ans1">This is test answer 112</span>
</div>
<br>
<div class="qbox">
<span class="qclass">Q. No.2) This is test question 110
<img id ="showAns2" class="icons" src="img/expand.png" onclick="javascript:showAns(2)" alt="show" width="20" height="20" style="float:right; cursor:pointer;">
<img id="hideAns2" class="icons" src="img/collapse.png" onclick="javascript:showAns(2)" alt="hide" width="20" height="20" style="float:right; display:none; cursor:pointer;">
</span>
<hr />
<span id="ans2">This is test answer 110</span>
</div>
<br>
这里的问题是我必须第一次单击图像三次,然后只有展开折叠才能正常工作。一旦我单击图像两次,展开折叠效果就很好。我不知道我做错了什么,任何帮助将不胜感激。谢谢。
最佳答案
你可以简单地这样做
$("[id^=ans]").hide();
$(".icons").click(function(){
$(this).closest("span").find("img").toggle();
$(this).closest(".qbox").find("[id^=ans]").slideToggle();
});
关于Javascript 函数无法按功能运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24695946/