0

当我单击一个元素时,我想取消绑定“mouseenter”和“mouseleave”事件,这可以正常工作,但是如果单击另一个元素,我想将它们重新绑定 - 这不起作用。

有什么帮助吗?

这是代码:

<script type="text/javascript">
  $(document).ready(function(){
        $("#shape1 img").click(function(){
          $("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").unbind('mouseenter mouseleave');
    });

     $("#close").click(function(){
        $("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").bind('mouseenter mouseleave');
     });
 });
</script>

非常感谢!

4

3 回答 3

0

因为您需要分配回调以在事件发生时执行。

尝试 :

<script type="text/javascript">
  $(document).ready(function(){
        var myFunctionMouseEnter = function(){
           alert('Hey');
        };
        var myFunctionMouseleave = function(){
           alert('Hey');
        };

        $("#shape1 img").click(function(){
          $("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").off('mouseenter mouseleave');
        });

        $("#close").click(function(){
            $("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").on('mouseenter',myFunctionMouseEnter )
                                                                               .on('mouseleave',myFunctionMouseleave );
        });
 });
</script>
于 2013-01-30T11:08:56.443 回答
0

bind 只会为当前存在的项目绑定事件处理程序。

来自文档Bind()

处理程序附加到 jQuery 对象中当前选定的元素,因此这些元素必须存在于调用 .bind() 的位置

使用 On 方法。

$("#shape1 img").click(function(){
          $("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").off('mouseenter');
        });

        $("#close").click(function(){
            $("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").on('mouseenter',myFunction1);
            $("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").on('mouseleave',myFunction2);
        });
于 2013-01-30T11:09:18.483 回答
0

.bind()函数希望您在触发这些事件时传递一个要执行的函数。

$("#shape1 img,#shape2 img, #shape3 img, #shape4 img, #shape5 img").bind('mouseenter mouseleave', function(event) {
    // do something here when the mouseenter or mouseleave events are triggered
});

当您调用.unbind()事件处理程序时,它会被完全删除,并且 jQuery 不会记住它是什么。您不能简单地调用.bind()来撤消它并让它知道它应该执行哪些代码来响应这些事件。

此外,根据您的 jQuery 版本(1.7+),您应该使用.on()and.off()函数来添加和删除事件处理程序。

于 2013-01-30T11:07:38.627 回答