jQuery - 如何查找 id 是否具有特定字符串?

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

jQuery - how can I find if an id has a specific string?

jquery

提问by AndreMiranda

I have a table and I want to know if its last td its id contains a certain string. For example, if my last td has id "1234abc", I want to know if this id contains "34a". And I need to do that in a 'if' statement.

我有一张表,我想知道它的最后一个 td 是否包含某个字符串。例如,如果我的最后一个 td 的 id 为“1234abc”,我想知道这个 id 是否包含“34a”。我需要在“if”语句中做到这一点。

if(myLastTdId Contains "blablabla"){ do something }

if(myLastTdId 包含“blablabla”){ 做某事 }

Thanks!!!

谢谢!!!

回答by CMS

You could use the "attributeContains" selector:

您可以使用“ attributeContains”选择器:

if($("#yourTable td:last-child[id*='34a']").length > 0) { 
   //Exists, do something...
} 

回答by Paolo Bergantino

This is easily done with indexOfand last-child.

这很容易用indexOf和完成last-child

<table id='mytable'>
<tr>
  <td id='abc'></td>
  <td id='cde'></td>
</tr>
</table>

<script>
if($('#mytable td:last-child').attr('id').indexOf('d') != -1) {
   alert('found!');
}
</script>

Here it would alert 'found' because dappears in the string cde

在这里它会提醒“找到”,因为d出现在字符串中cde

回答by Ben Blank

If your tdis "bare" (i.e. not wrapped in a jQuery object), you can access its idattribute directly:

如果您td是“裸机”(即未包装在 jQuery 对象中),您可以id直接访问其属性:

if (myTD.id.indexOf("34a") > -1) {
    // do stuff
}

If it isin a jQuery object, you'll need to get it out first:

如果在一个jQuery对象,你需要首先把它弄出来:

if (jMyTD[0].id.indexOf("34a") > -1 {
    // do stuff
}

The indexOffunction finds the offset of one string within another. It returns -1 if the first string doesn't contain the second at all.

indexOf函数查找一个字符串在另一个字符串中的偏移量。如果第一个字符串根本不包含第二个,则返回 -1。

Edit:

编辑:

On second thought, you may need to clarify your question. It isn't clear which of these you're trying to match "34a" against:

再三考虑,您可能需要澄清您的问题。目前尚不清楚您尝试将“34a”与以下哪些匹配:

  • <td id="1234abcd">blahblah</td>
  • <td id="blahblah">1234abcd</td>
  • <table id="1234abcd"><tr><td>blahblah</td></tr></table>
  • <table id="blahblah"><tr><td>1234abcd</td></tr></table>
  • <td id="1234abcd">blahblah</td>
  • <td id="blahblah">1234abcd</td>
  • <table id="1234abcd"><tr><td>blahblah</td></tr></table>
  • <table id="blahblah"><tr><td>1234abcd</td></tr></table>

回答by Scott Evernden

Not completely clear if you mean last td in each tr, or the very last td:

如果您的意思是每个 tr 中的最后一个 td 或最后一个 td,则不完全清楚:

if ($('#myTable td:last[id*=34a]').length) {
    ...
}