Home >Web Front-end >JS Tutorial >jquery prevents click, mouseover and mouseout bubbling problems to be solved
<ul> <li class="red"><a href="javascript:void(0)">项目一</a></li> <li class="green"><a href="javascript:void(0)">项目二</a></li> <li class="green"><a href="javascript:void(0)">项目三</a></li> <li class="green"><a href="javascript:void(0)">项目四</a></li> </ul> $(function () { $.each($("li"), function (i, o) { $(this).children("a").click(function () { allhide(); $(this).parent("li").attr("class", "red"); }); if ($(this).attr("class") != "red") { $(this).mouseenter(function () { $(this).attr("class", "red"); }); $(this).mouseleave(function () { $(this).attr("class", "green"); }); } }); }); function allhide() { $.each($("li"), function (i, o) { $(this).attr("class", "green"); }); } <style type="text/css"> li { width: 80px; list-style-type: none; } .red { background-color: Red; } .green { background-color: Green; } </style>
$.each($("li"), function (i, o) { $(this).children("a").click(function (e) { $("li").attr("class", "green");//不用另起函数 $(this).parent("li").attr("class", "red"); e.stopPropagation(); }); if ($(this).attr("class") != "red") { $(this).mouseenter(function (e) { $(this).attr("class", "red"); e.stopPropagation(); }); $(this).mouseleave(function (e) { $(this).attr("class", "green"); e.stopPropagation(); }); } });
doesn’t seem to work. The style of this li is changed when the mouse is clicked, but the style is removed when the mouse is moved away. I don’t know why
<script type="text/javascript"> //这里不存在冒泡呀 $(function () { $("li").each(function(){ $(this).find("a").click(function(){ $("li").attr("class","green"); $(this).parent().attr("class","red"); }) }); }); </script>
Oh , isn’t it bubbling? ? Then when I click here and move the mouse away, the style changes.
$(this).children("a").click(function () { allhide(); $(this).parent("li").attr("class", "red"); });
It seems to be a code problem. Can the following still be used after your $(this) pointer has been changed?
Use a variable to record var that = $(this) and try
if ($(this).attr("class") != "red") { $(this).mouseenter(function () { $(this).attr("class", "red"); }); $(this).mouseleave(function () { $(this).attr("class", "green"); }); } });
Well, I figured it out myself. When the mouse clicks on the event, the red style has been has changed, but I did not save the changed pointer. The following is my modified code:
nodeli = $("ul li:first"); $.each($("li"), function (i, o) { $(this).click(function () { allhide(); $(this).attr("class", "red"); nodeli = $(this); //alert(nodeli.html()); }); $(this).mouseover(function () { $(this).attr("class", "red"); }); $(this).mouseout(function () { $(this).attr("class", "green"); $(nodeli).attr("class", "red"); // alert(nodeli.html()); }); });
The above is the detailed content of jquery prevents click, mouseover and mouseout bubbling problems to be solved. For more information, please follow other related articles on the PHP Chinese website!