How can I simulate a mouseover event with jquery?

微笑、不失礼 提交于 2021-02-04 20:47:29

问题


I have a star rating system as defined like this:

<span class="rating_container"> 
    <span class="star_container">  
        <a rel="nofollow" href="" class="star star_1" >1<span class="rating">Terrible</span></a>   
        <a rel="nofollow" href="" class="star star_2" >2<span class="rating">Bad</span></a>
        <a rel="nofollow" href="" class="star star_3" >3<span class="rating">Bad</span></a>
        <a rel="nofollow" href="" class="star star_4" >4<span class="rating">OK</span></a>   
        <a rel="nofollow" href="" class="star star_5" >5<span class="rating">OK</span></a>   
        <a rel="nofollow" href="" class="star star_6" >6<span class="rating">OK</span></a>   
        <a rel="nofollow" href="" class="star star_7" >7<span class="rating">Good</span></a>   
        <a rel="nofollow" href="" class="star star_8" >8<span class="rating">Good</span></a>   
        <a rel="nofollow" href="" class="star star_9" >9<span class="rating">Excellent</span></a>   
        <a rel="nofollow" href="" class="star star_10" >10<span class="rating">Excellent</span></a>  
    </span> 
</span> 

Each individual star is colored when a mouseover happens. How can I simulate this with jquery? For instance I'd like to mouseover star 5. This is what I've tried:

     $('.star.star_5').addClass('active');

What am I missing?


回答1:


Try :

$(".star_5").trigger('mouseover');

This will trigger the mouseover action whatever it happens to be, rather than emulating it, offering a measure of future-proofing against changes to the mouseover handler.




回答2:


I think what you need is

$('.star.star_5').addClass('active');

Note the no-space between .star and .star_5 and the _ in star_5. (Thanks @wirey)




回答3:


In CSS (which is what jQuery selectors are based on), .class1 .class2 means "an element with class2 that has an ancestor with class1". This is not what you want. You want .class1.class2 which means "an element with both class1 and class2":

$('.star.star_5').addClass('active');



回答4:


In case you really want to simulate an event: You can trigger JavaScript events using parameterless forms of the corresponding jQuery functions. For example:

$('.star.star_5').mouseover();


来源:https://stackoverflow.com/questions/14246524/how-can-i-simulate-a-mouseover-event-with-jquery

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