javascript - 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
?
谢谢。
解决方案
您正在寻找.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);
});
推荐阅读
- ios - 基于 API 字段在启动时创建/修改 CoreData 实体(字段/元素)
- python - 使用 scikit learn 计算 pandas Dataframe 中各行之间的精度、召回率和准确率
- sparql - SPARQL 按日期范围过滤
- wordpress - 重命名添加到购物车以在 WooCommerce 上立即购买
- c# - efcore 5 中的多态集合
- reactjs - REACT JS,在react中显示一个sql“count”请求的结果
- ios - 从 CIIImage iOS swift 转换时如何修复 UIImage 方向
- nginx - grpc_next_upstream 未尝试 2 级代理中的下一个上游服务器
- r - 将 s 曲线添加到 r ggplot
- python - 运行 exe 文件时出现“ModuleNotFoundError”