jQuery 使用jQuery按标题选择一个div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9152551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:25:50  来源:igfitidea点击:

Select a div by title with jQuery

jqueryselecthtmltitle

提问by nick2k3

I have a webpage with a div which contains several other divs WITHOUT an ID associated to them:

我有一个带有 div 的网页,其中包含其他几个没有关联 ID 的 div:

<div id="container">
<div   title ="jhon" style=" position:absolute; left: 821px; top: 778.44px; width:8px; height:9px; z-index:3;"> </div> 
<div   title ="carl" style=" position:absolute; left: 561px; top: 579.88px; width:8px; height:9px; z-index:3;"> </div> 
</div>

I need to be able to search one of these div by title and then access its style attributes such as left and top.

我需要能够按标题搜索这些 div 之一,然后访问其样式属性,例如左和顶。

I am using jQuery but I have no idea on how to select an element by name. I've tried something like:

我正在使用 jQuery,但我不知道如何按名称选择元素。我试过这样的事情:

var c =$('div[title~="john"]');
alert(c);               //I get [object Object]
alert(c.style.left)     // throws an error and is undefined

but it seems not to work.

但它似乎不起作用。

Any help?

有什么帮助吗?

回答by Gigi

alert( $("div[title=\"john\"]").css("left") );
alert( $("div[title=\"john\"]").css("top") );

or, if the name is a variable:

或者,如果名称是变量:

var name = "john";
alert($("div[title=\""+name+"\"]").css("left"));
alert($("div[title=\""+name+"\"]").css("top"));

回答by Skyrel