开发者

How to compare all the IDs of <li> with an array of javascript or jquery?

开发者 https://www.devze.com 2023-03-21 22:29 出处:网络
I have an array like the following: aVN = new Array(); aVN.push(new Array(\'CET\', \'July\', \'Birthday\',\'20110704\'));开发者_Python百科

I have an array like the following:

aVN = new Array();
aVN.push(new Array('CET', 'July', 'Birthday',    '20110704'));开发者_Python百科
aVN.push(new Array('CGT', 'July', 'Anniversary', '20110705'));

I also have multiple <li> elements in my html like this:

<li id="thismonth">
   <ul>
      <li id="20110701">1</li>
      <li id="20110702">2</li>
      <li id="20110703">3</li>
      <li id="20110704" onclick="displayevent();" class="holiday">4</li>
      <li id="20110705">5</li>
   </ul>

I want to check whether 20110704 from the array aVN is present in the IDs of the <li>s.

If the ID and the array value match, then I want to display "Birthday" (the text from the array) when I click on that particular <li>.


<script type="text/javascript">

var aVN = [
    ['CET', 'July', 'Birthday',    '20110704'],
    ['CGT', 'July', 'Anniversary', '20110705']
];

function displayEvent(text) { // I'm not sure what you wanted to do here
    console.log(text);
}

$(function() {
   $('li.menu').click(function() {
      for (var i = 0; i < aVN.length; i++) {
          if (this.id == 'menu_' + aVN[i][3]) {
             displayEvent(aVN[i][2]);
          }
      }
   }).css({cursor: 'pointer'});
});
</script>

<ul>
   <li class="menu" id="menu_20110701">1</li>
   <li class="menu" id="menu_20110702">2</li>
   <li class="menu" id="menu_20110703">3</li>
   <li class="menu" id="menu_20110704">4</li>
   <li class="menu" id="menu_20110705">5</li>
</ul>

Live demo.

(Thanks to Damon for pointing out that IDs may not start with a numeric character.)


More "jquerysh" approach would be setting some class with common prefix and unique postfix (.allineed-1, .allineed-2 etc) and then finding content using appropriate css selector - $(document.body).find(".allineed-" + id). Nevertheless, if you insist, you can use ids the same way.

Besides, not sure, but looks like you'd better keep a hash instead of array, since ids are unique (if we do not care about ordering). It would be a bit easier to perform inverse action - to map lis for some data. Keeping in mind that, again, there are some more "jquerysh" approaches - using data to associate dom object with some, well, data )))


Try this

aVN = new Array();
aVN.push(new Array('CET', 'July','Birthday', '20110704'));
aVN.push(new Array('CGT', 'July','Anniversary', '20110705'));

for(var i = 0;i<avN.length;i++){
   if($("#"+avN[i][3]).length){
      $("#"+avN[i][3]).click(function(){
         alert(avN[i][2]);
      }
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消