简体   繁体   中英

Using jquery to change background of an element created with Jquery

I am trying to display search results on my page for a list of people then allow the user to select one of those search results.

I create a table of people using jquery, which each row having a class of .searchResult and I want to highlight (or change background) of that row on hover but it doesn't seem to work the way I'm doing it.

Is there an issue arising because they are rows that I have made after the page was loaded? Or is there an issue with changing the background color of a row?

JS

$(function(){
    $('.searchResult').hover(function(){
        $(this).css('background-color', '#ff0')
    });
});

Here is a jsfiddle for how I'm trying to allow an action on the newly created rpws: http://jsfiddle.net/uxWwZ/

You can do this with pure CSS:

.searchResult:hover td {
    background-color: #ff0;
}

http://jsfiddle.net/mblase75/6Pme2/

I would suggest going with the CSS answer, but if you must stay with JQuery, you need to use delegation since they are being added after page load.

$(function(){
    $(body).on('hover','.searchResult',function(){
        $(this).css('background-color', '#ff0')
    });
});

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