Javascript 函数无法按功能运行

标签 javascript jquery

我有以下 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();
});

Fiddle

关于Javascript 函数无法按功能运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24695946/

相关文章:

javascript - 使用 jquery 列出要淡入淡出的元素

javascript - DOM改变后如何绑定(bind)javascript事件

javascript - 使用 $routeParams,CSS 不会加载

javascript - AngularJs 通过调用 REST 端点触发文件下载

jquery - 保罗·爱尔兰的无限滚动不起作用

jquery - 事件下 zipper 接

javascript - 数字游戏算法

jquery - 在输入点击和附加图标上触发 jQuery datepicker 元素

javascript - 如何使用自定义属性创建/发布 Open Graph 对象实例/记录?

javascript - 使用字符串与属性名称进行 Angular 绑定(bind)