展开/折叠jquery

时间:2015-08-14 20:25:50

标签: javascript jquery

我正在尝试在网页上放置一个按钮,该网页使用jquery构建可折叠列表以展开/折叠所有列表。但是,我对jquery和javascript编码相当新,所以我遇到了一些问题。我已经放置了按钮,但它的代码没有响应,点击它后我在检查器中收到这个错误:“TypeError:HTMLInputElement不是一个函数(评估'ShowHide()')”我将如何纠正这段代码是否成功扩展/折叠?

按钮的代码在这里:

<script type="text/javascript" src="js/jquery-1.11.2.min.js">
document.getElementById('collapsible').addEventListener("click", ShowHide);

var collapsed = $('collapsible').hide();

function ShowHide(event) {

    if (collapsed == true) {
        $('collapsible').show();
        collapsed = false;
    }
    else {
        $('collapsible').hide();
        collapsed = true;
    }
}
</script>

id“collapsible”放置在正在展开/折叠的每个ul和li元素上。

按钮放置如下:

<input type="button" id="ShowHide" onclick="ShowHide()" value="Show/Hide">
编辑:我一直在尝试进行扩展/折叠,以便在此布局上使用。 jsfiddle.net/TLittler/9ndzm3cc

3 个答案:

答案 0 :(得分:3)

这就是我如何实现您正在寻找的效果。

&#13;
&#13;
$('#collapsible1').click("click", showHide);

var collapsible = $('.collapsible');
collapsible.hide();

function showHide() {
    if(collapsible.is(':hidden'))
        collapsible.show();
    else
        collapsible.hide();
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="collapsible1">Collapse</button>
<dl class="collapsible">
  <dh>List Header 1</dh><dl>List Item</dl><dl>List Item</dl><dl>List Item</dl>
</dl>
<dl class="collapsible">
  <dh>List Header 2</dh><dl>List Item</dl><dl>List Item</dl><dl>List Item</dl>
</dl>
<dl>
  <dh>List Header 3</dh><dl>List Item</dl><dl>List Item</dl><dl>List Item</dl>
</dl>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

document.getElementById('collapsible1').addEventListener("click", ShowHide);

var collapsed = $('collapsible').hide();

$('#ShowHide').click(function ShowHide(event) {

    if (collapsed == true) {
        $('collapsible').show();
        collapsed = false;
    }
    else {
        $('collapsible').hide();
        collapsed = true;
    }
})

你不应该使用onclick(),这是不好的做法。

此外,你有'collabsible'和'collapsible1'。我认为“可折叠”是你想要崩溃的项目吗?

答案 2 :(得分:0)

您可以尝试这样做。这可以在几行中完成,这是jquery的美丽:)。这是代码试一试:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#ShowHide").click(function() {
    if($("#collapsable").is(":hidden"))
        $("#collapsable").show("fast");
    else $("#collapsable").hide("slow");;
});
});         
    </script>



<div id="collapsable">Hello</div>
<input type="button" id="ShowHide"  value="Show/Hide">
相关问题