jQuery 在jquery中按类获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16280065/
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 text by class in jquery
提问by hlapointe
I want get test
inside this example. Why it doesn't work?
我想test
进入这个例子。为什么它不起作用?
HTML
HTML
<div id="partTypes">
<div class="partType">
<div class="details"> <span class="name">test</span>
</div>
<div class="buttons">
<input class="addCart" type="button" value="click me" />
</div>
</div>
</div>
JAVASCRIPT
爪哇脚本
$(document).ready(function () {
$('input.addCart').live('click', function () {
var $partType = $(this).closest('div.partType');
alert($partType.filter('span.name').text());
});
});
回答by j08691
Change:
改变:
alert($partType.filter('span.name').text());
to:
到:
alert($partType.find('span.name').text());
Ideally you also want to stop using .live()
and move to .on()
(since live was deprecated awhile ago and removed in 1.9) so the whole block would be:
理想情况下,您还希望停止使用.live()
并移至.on()
(因为 live 不久前已弃用并在 1.9 中删除),因此整个块将是:
$('input.addCart').on('click', function () {
var $partType = $(this).closest('div.partType');
alert($partType.find('span.name').text());
});
回答by Eyal
Try this:
尝试这个:
$(document).ready(function () {
$('input.addCart').click(function () {
var $partType = $(this).closest('div.partType');
alert($partType.find('span.name').text());
});
});
回答by Arun P Johny
.filter()
will apply the filter to the passed set of elements, where as you want to look at the descendent elements for which you need to use find()
.filter()
将过滤器应用于传递的元素集,您可以在其中查看需要使用的后代元素 find()
$(document).ready(function () {
$('input.addCart').live('click', function () {
var $partType = $(this).closest('div.partType');
alert($partType.find('span.name').text());
});
});
.filter(): Reduce the set of matched elements to those that match the selector or pass the function's test.
.filter():将匹配元素集减少到与选择器匹配或通过函数测试的元素集。
.find(): Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.find():获取当前匹配元素集合中每个元素的后代,由选择器、jQuery 对象或元素过滤。