Javascript jqueryget";这";来自if语句
我试图使用jquery从元素中获取一个唯一的值,这个值应该在我滚动到屏幕上的某个位置时出现。当元素出现在屏幕上时,postid15应该到达jquery代码 这是我的代码:Javascript jqueryget";这";来自if语句,javascript,jquery,Javascript,Jquery,我试图使用jquery从元素中获取一个唯一的值,这个值应该在我滚动到屏幕上的某个位置时出现。当元素出现在屏幕上时,postid15应该到达jquery代码 这是我的代码: $(document).scroll(function() { if($("p.viewedPost").is(':onScreen')) { var postId = $(this).attr("postId"); console.log("Element appeared on Sc
$(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”)
拥有这个
谢谢。您正在查找.filter()
和.each()
:
如果您的插件的:屏幕上的
选择器不能与.filter
一起工作,那么您可以将测试放在每个
回调中:
$("p.viewedPost").each(function () {
if (!$(this).is(':onScreen')) return; // skip
var postId = $(this).attr("postId");
console.log("Element appeared on Screen " + postId);
});
if语句没有自己的this
。你的逻辑是有缺陷的。考虑<代码> $(“P.VIEWEXPOST”)。每个(……)/代码>我理解,但是有没有办法去取它自己的“这个”呢?还是有其他方法可以解决我的问题?@AlexKudryashev如果$(“p.viewedPost:onScreen”)
返回多个元素怎么办?@PVPSquad不仅是下面trincot答案的简写(你说这不起作用),如果没有每个,它将只对选择中的第一个元素起作用。如果您在屏幕上同时有多个p.viewedPost
,您将只检索第一个的postId
。这不起作用,因为:屏幕上不支持“筛选”。这是一个自定义选择器-它如何支持.is()
,但不支持.filter()
?如果真的是这样的话,应该在问题中提及。见答案的补充。
$("p.viewedPost").each(function () {
if (!$(this).is(':onScreen')) return; // skip
var postId = $(this).attr("postId");
console.log("Element appeared on Screen " + postId);
});