hover not working for items in list

谁说我不能喝 提交于 2019-12-23 23:38:45

问题


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.



来源:https://stackoverflow.com/questions/18169739/hover-not-working-for-items-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!