【问题标题】:How can i execute the action only on the div,when i have multiple div with same class当我有多个具有相同类的 div 时,如何仅在 div 上执行操作
【发布时间】:2012-01-21 11:12:06
【问题描述】:

当我有多个具有相同类的 div 时,如何仅在 div 上执行操作

http://jsfiddle.net/kent93/Qw7bw/

当鼠标进入一个div时,另一个div也会有动作,请问如何解决

我只希望我的鼠标进入的 div 采取行动,而不是其他的,最好的解决方案是什么?

【问题讨论】:

  • 致 Dale Burrell:如果使用唯一的类或 id,则会出现一个问题,即稍后我添加另一个 div 时,我也必须手动添加相应的 javascript,效率不高

标签: javascript jquery html css mouseenter


【解决方案1】:

将每个位置的选择器更改为:$(this).children(".class")

例如代码$(".fromTopToBottom") 将更改为$(this).children(".fromTopToBottom")

演示: http://jsfiddle.net/Qw7bw/10/

【讨论】:

    【解决方案2】:

    很简单,用$(this),例如

    $('.mydivclass').mouseover(function(e){
        $(this).css('color','gray'); // Current element
    });
    

    如果 div 是嵌套的,那么您应该使用 e.stopPropagation() 来停止事件冒泡。

    【讨论】:

      【解决方案3】:

      您需要的是一个“当前”的 div 概念。

      1. 在 mouseenter 处理程序的开头:

        $(".trbl").removeClass("current"); $(this).addClass("current");

      2. 在您的案例陈述中,$(".fromTopToBottom").css({...}) -> $(".current .fromTopToBottom").css({...})

      效果查看http://jsfiddle.net/Qw7bw/7/

      【讨论】:

      • 你真是个天才,你的方式让每件事都变得如此高效,再次感谢
      【解决方案4】:

      在选择 ".fromTopToBottom" 和类似的类时,直接使用 $(this).find(x) 而不是 $(x)。这允许jQuery只选择悬停元素http://jsfiddle.net/Qw7bw/6/的子元素@

      【讨论】:

      • 很好,你的方法是在当前 div 中找到一些东西,谢谢
      【解决方案5】:

      使用$(this).children(".fromTopToBottom") 代替$(".fromTopToBottom")

      这将在您正在编写其处理程序的元素内选择给定类的 div。

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 1970-01-01
        • 2013-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-02
        • 1970-01-01
        • 2013-05-24
        相关资源
        最近更新 更多