javascript - jQuery 悬停功能不适用于 ng-repeat Angular 对象

标签 javascript jquery html css angularjs

我创建了一个 jQuery 悬停函数:

$('.deleteButton').hover(function(){
    $(this).css('opacity', '1');
},
function(){ 
    $(this).css('opacity', '.5');
});

当我将 HTML 元素硬编码到 index.html 文档中时它起作用了,但当我从模板中导入该元素时它不起作用。

模板如下:

<div class="logBox">
<div class="dateAndLocation">
    <p>{{ info.date | date }}</p>
    <p style="margin-top:-.7em">{{ info.location }}</p>
</div>
<div class="routeNameBox">
    <p class="routeName">{{ info.routeName }}</p>
    <p class="gradeAndType">{{ info.grade }} | {{ info.type }}</p>
</div>
<div class="timeAndLevelBox">
    <div class="timeBox pull-left">
        <p class="timeText">{{ info.time }}</p>
    </div>
    <div class="pclBox pull-right">
        <p class="pclText">{{ info.challengeLevel }}</p>
    </div>
</div>

<div class="notesBox">
    <p class="notesText">{{ info.notes }}</p>
</div>

<div class="photoCircle" style="background-image:url({{ info.photo }})"></div>
</div>

<div class="deleteButton"><p>&#8212;</p></div>

index.html代码:

<div class="container" style="min-width:1200px; margin:auto;" ng-repeat="climbLog in climbLogs">
    <climb-log info="climbLog"></climb-log>
<div>

它工作正常并按预期重复..但是当我将鼠标悬停在删除按钮上时,它不会改变它的不透明度,如 jQuery 函数中指定的那样(在我开始使用模板之前它已经工作)

最佳答案

眼前的问题是 $(...).hover(...) 只会收集现在存在的节点,并附加一个 hover 他们的处理程序。因此,任何可能最终与选择器匹配的 future 节点都不会在它们上面有处理程序。

使用 jQuery 的 on(具有实时选择器功能)解决了这个问题:$('#placeWithDeleteButtons').on('hover', '.deleteButton', ...)。这会将处理程序附加到捕获冒泡事件的祖先上,并检查触发后代是否与选择器匹配。因此,由于处理程序不在触发器上,您只需要一个处理程序来捕获任何当前或 future 匹配节点上的事件。

但是,如注释所示,如果您正在处理 Angular 元素,最好使用 Angular 的等效项。

编辑:确实,hover 必须分解为mouseentermouseleave:

$('.logBox').on("mouseenter mouseleave", ".deleteButton", function(evt) {
  $(this).css('opacity', evt.type === 'mouseenter' ? 1 : 0.5);
});
.deleteButton {
  opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logBox">
  <button class="deleteButton">Foo</button>
</div>

但是,如果您只想在悬停时更改不透明度,则有一种更简单的方法:

.deleteButton {
  opacity: 0.5;
}
.deleteButton:hover {
  opacity: 1;
}
  
<div class="logBox">
  <button class="deleteButton">Foo</button>
</div>

关于javascript - jQuery 悬停功能不适用于 ng-repeat Angular 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084909/

相关文章:

javascript - 按名称访问数组列表中的对象

javascript - 在 vue.js 中重新加载或关闭之前做一些事情

javascript - 用 JS 和 Canvas 增长无限循环

Jquery数据表基于行索引的操作

javascript - 未知提供者 : uniqueFilterProvider using unique filter in Angular. js

javascript - 如何在javascript中随机播放歌曲? (例如:从第5秒开始)

javascript - jQuery/javascript 和 setInterval 在 mouseenter 中无法正常工作

javascript - jQuery html 脚本 document.currentScript

html - 想用三种颜色在html中创建一条水平线

asp.net - 我是否需要添加一些特殊内容才能在 iPad 上正确查看我的网站?