jQuery按文本获取标签

jQuery按文本获取标签,jquery,jquery-selectors,label,selector,Jquery,Jquery Selectors,Label,Selector,我有一个简单的问题,我为它创建了一些丑陋的代码 我的问题是需要根据显示的文本获取标签,例如: <div class="editor-label"> <label for="iwantthisid">Test<span class="editor-label-required">* </span> </label> 测试* 因此,在这里,我希望搜索页面(尽可能快),以获取带有t

我有一个简单的问题,我为它创建了一些丑陋的代码

我的问题是需要根据显示的文本获取标签,例如:

    <div class="editor-label">
    <label for="iwantthisid">Test<span class="editor-label-required">*                </span>

    </label>

测试*
因此,在这里,我希望搜索页面(尽可能快),以获取带有text=“Test”的标签

然后,我想从该标签中提取“For”值

最好的方法是什么

我知道解决这部分的问题只需要
$(元素)。attr(“for”)
这是我被卡住的第一步

谢谢你用这个

$('label:contains(Test)').attr('for')

只需将id分配给标签,如下所示:

<label id="theLabel" for="iwantthisid">Test<span class="editor-label-required">*</label>
测试*
并通过
$(“#标签”).attr(“for”)获取值。我建议:

$('label').filter(function () {
    return this.firstChild.nodeValue.trim() === 'string';
}).attr('for');

如前所述,为了更好地保证(如果不需要精确的大小写,并为那些没有实现
String.trim()
)的浏览器提供):

要在功能上下文中使用此方法,请执行以下操作:

function getLabelByText(needle, caseSensitive) {
    var str;
    return $('label').filter(function(){
        str = $.trim(this.firstChild.nodeValue);
        return caseSensitive ? str === needle : str.toLowerCase() === needle.toLowerCase();
    });
}

console.log(getLabelByText('Test',false));


这些不同的方法取决于您正在搜索的文本是
标签
元素的
第一个孩子
(根据您在问题中提供的当前HTML做出决定)。

谢谢,您认为这是最理想的搜索方法吗?@LmC-当然不是,但它是有效的,当然,这也会匹配
测试测试
我有一个测试
,这可能是一个问题@Blazemonger-标签还包含
*
,所以这可能不是问题?我如何使用参数调用该函数?除了
trim()
对字符串进行处理外,您可能会发现将其转换为
toLowerCase()会很有帮助
在某些情况下。搜索文本的全部原因是我们无法控制ID。
function getLabelByText(needle, caseSensitive) {
    var str;
    return $('label').filter(function(){
        str = $.trim(this.firstChild.nodeValue);
        return caseSensitive ? str === needle : str.toLowerCase() === needle.toLowerCase();
    });
}

console.log(getLabelByText('Test',false));