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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:51:15  来源:igfitidea点击:

get text by class in jquery

jqueryhtml

提问by hlapointe

I want get testinside 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());
});

jsFiddle example

jsFiddle 示例

回答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 对象或元素过滤。