包含返回多个值

问题描述 投票:0回答:1

我正在使用

$('label:contains('something');
来获取其中包含“某物”的标签 它工作得很好,但我希望能够处理多个标签如何做到这一点 示例:

HTML:

<html>    
<label for='michel'>My Name is Michel</label>
    <label for='allen'>My Name is Allen</label>
    <label for='chris'>His Name is Chris</label>
</html>

jQuery:

<script>    
label = $('label:contains(My Name is)');
    console.log(label.attr('for'));
</script>

现在控制台只记录 michel 我希望能够处理多个值,我想记录 michel 和 allen

javascript html jquery jquery-selectors
1个回答
0
投票

您可以使用 jQuery each 函数来迭代所有标签。

let labels = $('label:contains(My Name is)');

labels.each(function(){
  console.log($(this).attr('for'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for='michel'>My Name is Michel</label>
<label for='allen'>My Name is Allen</label>
<label for='chris'>His Name is Chris</label>

© www.soinside.com 2019 - 2024. All rights reserved.