Select a div by title with jQuery

泪湿孤枕 提交于 2019-12-24 00:46:06

问题


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

<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.

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

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?


回答1:


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"));



回答2:


try

$("div[title~=john]"); //no quotations inside

Attribute Contains Word Selector [name~="value"]



来源:https://stackoverflow.com/questions/9152551/select-a-div-by-title-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!