gpt4 book ai didi

jQuery:按数据属性选择某些元素失败 - 为什么?

转载 作者:行者123 更新时间:2023-11-28 05:01:00 24 4
gpt4 key购买 nike

给定 HTML 代码:

<div id="details" data-type="motion">
<p>Lorem ipsum</p>
</div>
<img src="http://placehold.it/50x50" data-type="motion" />
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidun...</p>

为什么下面脚本的选择器不能正常工作?

$(document).ready(function () {

$('[data-type="motion"]').each(function() {

$this = $(this);

$(window).bind('scroll', function() {

var yOffset = (window.pageYOffset / $this.data('speed')) + 'px';

$this.css({'border': '1px solid red'});
});

});

});

使用'[data-type="motion"]',只有图像被选中。当然是'div[data-type="motion"]'只选择具有该数据属性的 div。 '*[data-type="motion"]' 也只匹配图像 & 'img[data-type="motion"], div[data-type="motion"] ' 似乎有点多余,而且也不起作用。

这是一个演示该行为的 fiddle :http://jsfiddle.net/Y7QXn/

最佳答案

问题不在于选择器,而在于非本地的局部变量:

$this = $(this);

这将创建一个全局变量,因此每个元素的事件处理程序都会影响最后一个元素。

让它成为局部变量:

var $this = $(this);

关于jQuery:按数据属性选择某些元素失败 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15269232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com