简体   繁体   中英

Click event only works on second post

The below function works only after the page has been refreshed. When the page is refreshed again afterwards it stops working again and so on.

<button id="moreBtn" type="button" class="archive btn btn-default col-sm-12"></button>
function ShowHideBtn() {
    var newss = 5;
    var numItems = $(".news").length;
    hidenews = "- Show Less Products";
    shownews = "+ Show More Products";

    $(".news:not(:lt(" + newss + "))").hide();
    $("hr:not(:lt(" + newss + "))").hide(); 

    if (numItems >= newss) {
        $(".archive").show();
        $(".archive").html(shownews);

        $(".archive").on("click", function (e) {
            e.preventDefault();
            if ($(".news:eq(" + newss + ")").is(":hidden")) {
                $("hr:hidden").show();
                $(".news:hidden").show();
                $(".archive").html( hidenews );
            } else {
                $("hr:not(:lt(" + newss + "))").hide();
                $(".news:not(:lt(" + newss + "))").hide();
                $(".archive").html(shownews);
            }
            return false; 
        });
    } else {
        $(".archive").hide();
    }
}

Thanks in advance

This is a guess as there is insufficient information to confirm it. Please provide the full page HTML/code:

As browser page requests are stateless (so it can't know it is every other load), this sounds like a timing issue. The HTML would generally load slower the first time, so if the JS code is not positioned after the element it references (or is inside a DOM ready handler), then it may fail to find the .archive element. It is more likely random than "every other page load" though if it is a timing issue.

Try one of the following:

  1. Place your JS code (or JS script include) after the element they reference. Just before the closing </body> tag is typical for this option.
  2. Place your code inside a DOM ready handler, then its position does not matter. eg like:

    $(document).ready(function(){ // Your code here });

or the short-cut version of DOM ready:

$(function(){
     // Your code here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM