javascript id 包含 Jquery 中的特定字符串名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14829553/
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
id contains specific string name in Jquery
提问by smith
I've a tmp variable. If a tag id contains tmp string want to addClass. How to do?
我有一个 tmp 变量。如果标签 id 包含 tmp 字符串要添加类。怎么做?
$(document).ready(function () {
var tmp = "#lnkPage" + id;
$("#pageingdiv").children().each(function (n, i) {
var id = this.id;
//if (id.contains(tmp)) {
// $(id).addClass('box');
//}
});
});
<div id="pageingDiv">
<a id="CPH_Content_C002_lnkPage1" ></a>
<a id="CPH_Content_C002_lnkPage2" ></a>
<a id="CPH_Content_C002_lnkPage3" ></a>
<a id="CPH_Content_C002_lnkPage4" ></a>
</div>
</div>
回答by asifsid88
use indexOf()
利用 indexOf()
if(id.indexOf(tmp) !== -1)
{
$(id).addClass('box');
}
Moreover you should not have elements with same ID, you should use class instead
此外,您不应该拥有具有相同 ID 的元素,而应该使用 class
回答by Gung Foo
Look at the Attribute starts with, Attribute ends withand Attribute containsSelectors. They will help you select all the elements you want directly without the need to call any other functions than .addClass()
. :)
看看属性开头,属性结束与和属性包含选择器。它们将帮助您直接选择所需的所有元素,而无需调用除.addClass()
. :)
回答by Dipesh Parmar
You can use jQuery( "input[id*='value']" )
Selector to check if its contain specific string as ID.
您可以使用jQuery( "input[id*='value']" )
Selector 检查其是否包含特定字符串作为 ID。
Tested Code
测试代码
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function()
{
$( "a[id*='lnkPage']" ).addClass('SampleClass');
});
</script>
<div id="pageingDiv">
<a id="CPH_Content_C002_lnkPage1" ></a>
<a id="CPH_Content_C002_lnkPage1" ></a>
<a id="CPH_Content_C002_lnkPage1" ></a>
<a id="CPH_Content_C002_lnkPage1" ></a>
</div>
回答by Debasish Chowdhury
Try this
试试这个
var tmp = "lnkPage1";
$("a[id*='"+tmp+"']").addClass('box');
回答by Jai
Try this:
试试这个:
var tmp = "lnkPage" + id; // <-----remove the hash '#'
$('[id$="'+tmp+'"]').addClass('box');