Javascript 如何在javascript中选择包含某个字符串的所有id标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8126218/
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-24 04:47:26  来源:igfitidea点击:

How do you select all id tags that contain a certain string in javascript?

javascriptjqueryasp.net

提问by Alex

I have an ASP.NET application that renders multiple questions with the option to provide an explanation for the answers given.

我有一个 ASP.NET 应用程序,它呈现多个问题,并提供对给出的答案进行解释的选项。

<label for="[<%:count %>].AnswerExplanation_<%: i+1 %>" id="[<%:count %>].toggleExplanation_<%: i+1 %>"><strong>Add Explanation</strong></label>
<br /><br />
<div id="[<%:count %>].Explanation_<%: i+1 %>">
    <textarea id="[<%:count %>].AnswerExplanation_<%: i+1 %>" name="[<%:count %>].AnswerExplanation_<%: i+1 %>" class="ckedit"></textarea>
</div>

so you will have id's like "[X].toggleExplanation_Y" corresponding to "[X].AnswerExplanation_Y"

所以你会有像“[X].toggleExplanation_Y”这样对应于“[X].AnswerExplanation_Y”的id

I am writing a javascript function to show/hide the AnswerExplanation divs, and was looking for a way to select every id containing "toggleExplanation" I should be able to get the rest from there.

我正在编写一个 javascript 函数来显示/隐藏 AnswerExplanation div,并且正在寻找一种方法来选择包含“toggleExplanation”的每个 id,我应该能够从那里获得其余部分。

回答by John Hartsock

Try using the attribute contains collector

尝试使用包含收集器属性

$('label[id*="toggleExplanation"]')

回答by Niels

If your using jquery you can use this to select everything containing "toggleExplanation"

如果您使用 jquery,您可以使用它来选择包含“toggleExplanation”的所有内容

$("[id*='toggleExplanation']") 

回答by Leon

Give all the .toggleExplanation_divs a unique marker CSS class. Then you can simply use jQuery to select all elements with that class.

给所有的.toggleExplanation_div 一个唯一的标记 CSS 类。然后您可以简单地使用 jQuery 选择具有该类的所有元素。