最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hide all elements with particular number in id - Stack Overflow

programmeradmin4浏览0评论

need help, I try to cut plexity and make simple example:

<div id="tree_div">
   <ul>
      <li id="tree_li_401">401</li>
      <li id="tree_li_101">101</li>
      <li id="tree_li_301">301</li>
      <li id="tree_li_201">201</li>
      <li id="tree_li_102">102</li>
      <li id="tree_li_402">402</li>
   </ul>
</div>

I need to hide all li elements base on first number after tree_li_

For example: I need to hide all elements which have number 4 after tree_li_:

<li id="tree_li_402">
<li id="tree_li_401">

need help, I try to cut plexity and make simple example:

<div id="tree_div">
   <ul>
      <li id="tree_li_401">401</li>
      <li id="tree_li_101">101</li>
      <li id="tree_li_301">301</li>
      <li id="tree_li_201">201</li>
      <li id="tree_li_102">102</li>
      <li id="tree_li_402">402</li>
   </ul>
</div>

I need to hide all li elements base on first number after tree_li_

For example: I need to hide all elements which have number 4 after tree_li_:

<li id="tree_li_402">
<li id="tree_li_401">
Share Improve this question asked Nov 16, 2012 at 2:29 xsorxsor 1,07411 silver badges11 bronze badges 1
  • api.jquery./attribute-starts-with-selector – Derek 朕會功夫 Commented Nov 16, 2012 at 2:51
Add a ment  | 

2 Answers 2

Reset to default 11

You can use attribute selectors to target those elements:

$('li[id^="tree_li_4"]').hide();

Here's a list of all the attribute selectors that jQuery supports.

As stated, you can use attribute selectors, if you would like a solution for all of them, use the .each() method, and you could use a variable for the number.

example:

$("li[id='tree_li_'"+ magicNumber +"]").each(function (idx, li) {
  $(li).hide();
});

or as a one liner

$("li[id='tree_li_'"+ magicNumber +"]").hide();

and if you wanted to get really crazy, you could use the .substring() method. .substring returns true, if the string has the specified substring. i.e. "brian".substring("ria") will return with the index of the string (a positive number) and if it does not find the string, it returns as -1.

$("li").each(function(idx, li) {
  if ($(li).attr("id").substring("4")) {
    $(li).hide();
  }
});
发布评论

评论列表(0)

  1. 暂无评论