首页 > 解决方案 > Jquery 从 if 语句中获取“this”

问题描述

我正在尝试使用 jquery 从元素中获取唯一值,当我滚动到屏幕上的某个位置时,应该会出现这个值。当元素在屏幕上时,postId 15 应该到达 jquery 代码。

这是我的代码:

$(document).scroll(function() {
    if($("p.viewedPost").is(':onScreen')) {
        var postId = $(this).attr("postId");
        console.log("Element appeared on Screen " + postId);
    }
    else {
        console.log("Element not on Screen");
        //do all your stuffs here when element is not visible.
    }
});

问题是我有多个 postId,所以我不能使用$("p.viewedPost").attr("postId");

它需要是$(this).attr("postId");

但是当我使用“this”时,postId 似乎是未定义的。那么我怎样才能得到$("p.viewedPost").is(':onScreen')一个this

谢谢。

标签: javascriptjquery

解决方案


您正在寻找.filter().each()

$("p.viewedPost").filter(':onScreen').each(function () {
    var postId = $(this).attr("postId");
    console.log("Element appeared on Screen " + postId);
});

如果您的插件的:onScreen选择器不适用于.filter,那么您可以将测试放在each回调中:

$("p.viewedPost").each(function () {
    if (!$(this).is(':onScreen')) return; // skip
    var postId = $(this).attr("postId");
    console.log("Element appeared on Screen " + postId);
});

推荐阅读