简体   繁体   中英

jquery .click function not getting triggered

I have the following HTML and Javascript code. I am trying to make a search suggestion system. The list-items in the unordered-list 'search_suggest' are retrieved dynamically using ajax as the user types in the input box 'site_search' and inserted.

<form name="search_site_form" method="get" action="search.php">
        <input id="site_search" name="q" class="search_input input" autocomplete="off" value="Search the site" type="text"/>

    <ul id="search_suggest">
    </ul>
    <input value=" " type="submit" class="search_submit"/>
    <script type="text/javascript">
    <!--
        $("ul#search_suggest>li").click(function(){ 
        alert('123');
    });
    //-->
    </script>
</form>

Clicking on the list items in search_suggest however is not triggering the click function. Any idea why?

You need to bind the click event to the list items after they have been added to the page.

Before any list items get added to the page, the expression $("ul#search_suggest>li") finds nothing, so no elements get bound to the click event.

You need to use .live that will:

Attach a handler to the event for all elements which match the current selector, now and in the future

Like the following:

<script type="text/javascript">
<!--
    $("ul#search_suggest>li").live('click', function(){ 
    alert('123');
});
//-->

Your script is running once, binding the onclick action to non-existent <li> elements. You will need to build into your AJAX script something that will add the onclick to each <li> element as they are added to the DOM.

use the jQuery.live();

 <script type="text/javascript">
    <!--
        $("ul#search_suggest>li").live('click', function(){ 
        alert('123');
    });
    //-->
    </script>

Use

$("ul#search_suggest+input").click(function(){ 
        alert('123');
    });

Here the input tag is the next sibling of an ul with id earch_suggest
+ is the jQuery Next Sibling Selector

The selector "ul#search_suggest>li" means find the li which is the child of the ul with id search suggest.
> is the jQuery Child Selector

向其中添加空li或具有值的li并像这样<ul id="search_suggest"> <li></li> </ul>

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