hover not working for items in list

2019-07-12 02:24发布

问题:

Honestly not sure what I'm doing wrong- I want to add a highlight effect on hover for items in a list. The html is below:

    <div class="list">
        <h3 id="mainlist">YOUR LIST:</h3>
        <input type="text" class="newitem">
        <div class="additem">ADD</div>
        <ul></ul>
    </div>

And what I have of jquery is as follows:

$(document).ready(function() {
    $('.additem').click(function() {
        $('ul').append('<li class=listitem><span>' + $('.newitem').val() + '</span></li>');
    });
    $('.listitem').live ('click',function() {
        $(this).remove();
    });
    $('span').hover(function() {
        $(this).toggleClass('hover');
    });
});

Everything works until the toggleClass part, nothing seems to happen when I hover over things. It's not a browser issue, the hover works fine with other html elements that aren't inside the list. I have also tried changing 'span' to 'li' instead, but that didn't work either.

Would really appreciate any help with this. Thanks!

回答1:

It is CSS' job! If all what a hover handler is doing is toggling a class , so do it like this:

<style>
  li.listitem span:hover{
  /* CSS Rules */
  }
</style>


回答2:

just do:

<style>
  li.listitem span:hover{
  /* some CSS */
  }
</style>


回答3:

Try this:

$(document).ready(function() {
$('.additem').click(function() {
    $('ul').append('<li class=listitem><span>' + $('.newitem').val() + '</span></li>');
 $('span').hover(function() {
    $(this).toggleClass('hover');
 });
});
$('.listitem').live ('click',function() {
    $(this).remove();
});

});

Basically you are assuming that the "hover" event handler will be attached to the spans even when they were not in the dom. You must attach an event to the element after it has been created.