jQuery 获取子元素的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4740297/
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
Get attribute of child element
提问by PruitIgoe
If I have the following markup:
如果我有以下标记:
<p class="header hours">
<a href="javascript:void(0)" class="sort" sortcat="hours">
Hours <span class="imgholder" sortcat="hours"> </span>
</a>
</p>
How can I target the <span>
tag within the anchor tag? There are five other similar <p>
tag entries, each with a different value for sortcat=
如何<span>
定位锚标签中的标签?还有其他五个类似的<p>
标签条目,每个条目都有不同的值sortcat=
回答by mkoryak
$(".sort").click(function(){
var cat = $(this).children("span").attr("sortcat");
//do something with the sortcat
});
回答by Brian Donovan
$("a span[sortcat]").attr('sortcat')
That'll give you the first element's sortcat
value. To get all of them, do this:
这会给你第一个元素的sortcat
值。要获得所有这些,请执行以下操作:
$("a span[sortcat]").map(function(){ return $(this).attr('sortcat') })
See this working demo: http://jsfiddle.net/BwgDW/
看到这个工作演示:http: //jsfiddle.net/BwgDW/
回答by sdleihssirhc
$('.sort span')
Did I misunderstand?
我误会了吗?
回答by TJ Kirchner
There's a couple of ways you can reference the span tag, but all of them end with " .attr('sortcat'); " I guess it depends on how specific you want to be and how flexible you need to be if there's a few other p tags with anchor tags and spans inside.
有几种方法可以引用 span 标签,但所有方法都以“.attr('sortcat');”结尾,我想这取决于您想要的具体程度以及您需要的灵活性(如果有一些)其他带有锚标签和跨度的 p 标签。
$('p.header a.sort span.imgholder').attr('sortcat');
/* or */
$('span.imgholder').attr('sortcat');
You can select elements based upon their tag name, their class name, or by the attributes inside the tags. Refer to jQuery's documentation on selectors:
您可以根据标签名、类名或标签内的属性来选择元素。参考jQuery关于选择器的文档:
http://api.jquery.com/category/selectors/basic-css-selectors/
http://api.jquery.com/category/selectors/basic-css-selectors/
回答by scragz
find() finds elements within a given element.
find() 在给定元素中查找元素。
$('a.sort').find('span');
$('a.sort').find('span');