简体   繁体   English

使用带有jQuery的name属性访问anchor元素

[英]Accessing an anchor element using name attribute with jQuery

I like to access an anchor (a) element with a specific name in jQuery to obtain its position. 我喜欢在jQuery中访问具有特定名称的anchor(a)元素以获取其位置。 I tried the following: 我尝试了以下方法:

HTML: HTML:

<a name="test">An anchor.</a>

JavaScript: JavaScript的:

var top = $("a [name=test]").position().top;

Returns empty object. 返回空对象。

var top = $("a").position().top;

and

var top = $("[name=test]").position().top;

finds it. 找到它。 How do I write it to get an anchor element with name "test"? 如何编写它来获取名为“test”的锚元素?

You don't need space after a in your selector: 之后,你不需要空间, a在您选择:

var top = $("a[name=test]").position().top;

If you put space then it'll find the child elements with name test of any anchor instead. 如果你放置空间,那么它将找到具有任何锚点的名称test的子元素。

Remove the space : 删除空格:

var top = $("a[name=test]").position().top;

A space indicates that you're looking for a child element. 空格表示您正在寻找子元素。

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

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