简体   繁体   English

使用带有jQuery的索引获取表的偏移位置

[英]Get the offset position of a table using its index with jQuery

I have two tables in a page. 我在一个页面中有两个表。 And i print their top co-ordinates using jQuery's $.offset().top . 我使用jQuery的$.offset().top打印他们的顶级坐标。

$("table").offset().top 

prints the first table offsets. 打印第一个表偏移量。 Doesn't $("table") select all the tables? 不是$("table")选择所有表吗? How does it print just the first table's co-ordinates? 它如何打印第一张表的坐标?

And when i try to print the second table's offset position using $("table")[1] , it says $("table")[1].offset is undefined 当我尝试使用$("table")[1]打印第二个表的偏移位置时,它表示$("table")[1].offset undefined

Jsfiddle link is at, http://jsfiddle.net/JfGVE/805/ Jsfiddle链接在, http://jsfiddle.net/JfGVE/805/

Note: I can get the results using table's id but i am looking for a solution that uses table's index to get its offset 注意:我可以使用表的id获取结果,但我正在寻找使用表索引来获取其偏移量的解决方案

You can't use jQuery methods on DOM elements. 您不能在DOM元素上使用jQuery方法。

A jQuery object contains DOM elements, and you were trying to use the jQuery method .offset() on one of the DOM elements in the jQuery object. jQuery对象包含DOM元素,并且您尝试在jQuery对象中的一个DOM元素上使用jQuery方法.offset()

Use the .eq() method in order to access a jQuery object by its index instead: 使用.eq()方法 ,以便通过索引访问jQuery对象:

$("table").eq(1).offset().top;

(As a side-note, the .eq() method's index is zero-based, so .eq(1) is the second element.) (作为旁注, .eq()方法的索引是从零开始的,所以.eq(1)是第二个元素。)


It's also worth mentioning that you can wrap the DOM element $("table")[1] with $() in order to use it as a jQuery object: 还值得一提的是,您可以使用$()包装DOM元素$("table")[1] ,以便将其用作jQuery对象:

$($("table")[1]).offset().top

jquery docs for offset(): offset()的jquery文档:

Get the current coordinates of the first element in the set of matched elements, relative to the document. 获取相对于文档的匹配元素集中第一个元素的当前坐标。

says it all 这一切都说明了

You can either iterate over the tables and store their offset in an array. 您可以迭代表并将其偏移量存储在数组中。 When you access the table as $("table")[1], it becomes a javascript object. 当您以$(“table”)[1]的形式访问该表时,它将成为一个javascript对象。 In order to get the offset for this element you can use any of the following: 要获取此元素的偏移量,您可以使用以下任何一种方法:

$("table").eq(1).offset().top

or 

$($("table")[1]).offset().top

This is because .offset() is a jquery function and not a javascript funtion. 这是因为.offset()是一个jquery函数而不是一个javascript函数。

您可以使用.eq()代替。

console.log("the first table offset is " +$("table").eq(1).offset().top)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM