jquery 嵌套选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3890458/
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
jquery nested selector
提问by holden
How can I grab the nested element "4"?
如何获取嵌套元素“4”?
I tried:
我试过:
var nights = $("div.nights h5 div.num").val();
and:
和:
var nights = $("div.nights > h5 > div.num").val();
example:
例子:
<div class="nights">
<h5 class="biguns">
<div class="num">4</div>
Nights
</h5>
</div>
回答by Nick Craver
Use .text()
here instead, like this:
使用.text()
此相反,像这样:
$("div.nights h5 div.num").text()
//or this works too:
$("div.nights > h5 > div.num").text()
//or just
$("div.num").text();
You can test it here, as you can see above, your selector is flexible, use what works on your overall markup. .val()
is for input type elements, e.g. <input>
, <select>
, <textarea>
, <button>
...to get the text inside of any other element, use .text()
instead.
你可以在这里测试它,正如你在上面看到的,你的选择器是灵活的,使用对你的整体标记有效的东西。 .val()
用于输入类型元素,例如<input>
, <select>
, <textarea>
, <button>
... 要获取任何其他元素内的文本,请.text()
改用。
回答by Amitābha
$("div.nights div").text()
but not
但不是
$("div.nights > div").text()
because descendant selector: A descendant of an element could be a child, grandchild, great-grandchild, and so on, of that element. child selector: Selects all direct child elements specified by "child" of elements specified by "parent".
因为后代选择器:元素的后代可以是该元素的子元素、孙子元素、曾孙子元素等等。子选择器:选择由“父”指定的元素的“子”指定的所有直接子元素。
reference child selectordescendant selector