简体   繁体   中英

Jquery doesn't work on HTML tags which via called by AJAX

i have an unordered list

<ul id="showlist"></ul>

if user calls ajax function this fills with list items like

<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li> 
</ul>

my problem begins after that. i have a <script> tag at the very and of my page. it says when down button is pressed make first child of <ul> blue. but it does nothing

<script>

$(body).keydown(function(e) {
    if(e.keyCode == 40){
        $("#showlist:first-child").attr("style","background-color:blue");       
    }
})

</script>

how can i solve my problem?

Use $('body') instead of $(body) .

You also have an issue with your selector:

$("#showlist li:first-child")

Working example: http://jsfiddle.net/hF6LF/

Also, you mentioned in your post that this script is at the end of the page. If you had the script in the head, you would need to wait for dom ready for the body element to exist. It might be safer to bind the handler to document , which will always exist.

Use .on jquery method

$(body).on("keydown", function(e) {
   .....
});

Jquery .on()

Yo have to use the on event listener which can handle events on descendant elements not yet created.

See https://api.jquery.com/on/

For example something like the following.

$(document).on( "keydown", "body", function() {
  alert( $( this ).text() );
});

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