Jquery hide不能在.on()中工作

Jquery hide not working inside .on()

本文关键字:工作 on hide 不能 Jquery      更新时间:2023-09-26

我正在加载div帮助页面到index.html内的div。加载在我的index.html页面上正常工作。问题是,一旦帮助页div加载到index.html的div下的helpSection全部出现,不消失,直到我能够单击其中一个div。我想要的是只有第一个helpDiv显示和所有其他隐藏,如果这是不可能的,只是所有div隐藏。我试过玩jquery代码,但一直无法成功地得到这个工作。

jsfiddle例子

任何帮助都将是非常感激的。

index . html

<body>
    <div id="loadHelpHere"></div>
</body>

Html代码

<div id="helpPage">
    <div id="helpMenu">
         <h4>Help Menu</h4>
        <ul id="menu">
            <li class="current_page_item justClick"><a href="#" data-id="div1">Help Section 1</a>
            </li>
            <li class="justClick"><a href="#" data-id="div2">Help Section 2</a>
            </li>
        </ul>
    </div>
<div id="helpSection">
    <div class="helpDiv">
        <header>Help Documentation</header>
        <article>Works!</article>
    </div>
    <div class="helpDiv1">
        <header>Help Documentation content 1</header>
        <article>Help Section 1</article>
    </div>
    <div class="helpDiv2">
        <header>Help Documentation content 2</header>
        <article>Help Section 2</article>
    </div>
</div>

jquery

$(document).ready(function(){
    $( "#loadHelpHere" ).load( 'help.html #helpPage' );
    $(document).on('click', '.justClick', function (e) {
        $('#helpSection div').not(".helpDiv").hide();
        $('#helpSection div.helpDiv').html($('#helpSection div.helpDiv' + ($(this).index() + 1)).html());
    });
});

我会在每个<div class="helpDiv">上设置style="display: none",除了第一个"helpDiv"或放置一些css,如:

/* This will target classes containing the string "helpDiv" but not the class helpDiv */
[class*="helpDiv"]:not(.helpDiv) { 
    display: none;
}

然后像这样输入.justClick:

$(document).on('click', '.justClick', function (e) {
    // This will hide all divs that contain a class matching "helpDiv"
    $('#helpSection [class*="helpDiv"]').hide();
    // Grab the index of the current .justClick
    var index = $(this).index() + 1;
    // Show the corresponding "helpDiv"
    $('#helpSection div.helpDiv' + index).show();
});

jsfiddle更新

所以要么添加一个CSS类来默认隐藏它们,要么在加载完成时将它们设置为隐藏。

#helpSection > div {
    display : none;
}

您可以显示默认的内容并删除内容,或者只是切换元素的可见性,而不是替换默认的内容。

https://jsfiddle.net/pt74q4dk/1/

set style="display:none;"在默认情况下您希望隐藏的div上,然后是$。当你需要的时候再给他们看。

$(document).ready(function(){
    $( "#loadHelpHere" ).load( 'help.html #helpPage' );
    $( "#loadHelpHere" ).find('#helpSection').hide();
});

还缺少div#loadHelpHere的结束标签