简体   繁体   中英

JQuery click event fires on second click but not on first in search form

I do my search form and use Jquery. So it works, it shows me result, but ONLY on the second time. When I click it on the first time - it shows all blocks.

 $(document).ready(function(){ $('#search').click(function () { text = $('#search_word').val(); $(".return").fadeIn('slow'); $('.topic_retain:contains("' + text + '")').css("display", "block"); $('.question_block:contains("' + text + '")').fadeIn(); }); $(".go_back").click(function(){ $('.search_topic').fadeIn(); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="search" placeholder="Search" id="search_word"><button id="search">Search</button> <div class="return"><span class="go_back">Go Back</span></div> <div class="topic_retain"> <h1>Retain</h1> <div class="question_block"> <div class="question"><span class="q">First question</span></div> <div class="answer">First answer.</div> </div> <div class="question_block"> <div class="question"><span class="q">Second question</span></div> <div class="answer">Second question</div> </div> <div class="question_block"> <div class="question"><span class="q">Third question</span></div> <div class="answer">Third answer. </div> </div> </div> 

actually in your JS-Code you are not targeting elements that are visible in your Html-Code. However you have forgotten the "});" to close the "$(document).ready(function(){".

so just add this to the end, and it should fire normally. Js should look like this:

$(document).ready(function(){
  $('#search').click(function(){
    text = $('#search_word').val();
    $(".return").fadeIn('slow');
    $('.topic_retain:contains("'+text+'")').css("display", "block");
    $('.question_block:contains("'+text+'")').fadeIn();
    $('.topic_container').fadeOut();
    $('.search_container').fadeOut();
    $('.search_topic').fadeOut();
  });
});

Hope it helps :)

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