Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

javascript - search whether id consists of dynamic value

The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"? The value[RANKS] is dynamic from 1-50

var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
  var a = 1;
  ranking = "<div > " +
    ("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
    ("<div>" + rankingList[i].username + "</div>") +
    ("<div>" + rankingList[i].winningAmt + "</div>") +
    ("<div> " + rankingList[i].uCoin + "</div>") +
    (" </div>");
};

Expected result:

  1. A
  2. A
  3. B
  4. B
  5. C
  6. B
  7. A
  8. A
  9. B
  10. G

so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)

question from:https://stackoverflow.com/questions/65844056/search-whether-id-consists-of-dynamic-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.

If you want it to check inside loop:

var ranks = {};

for (var i = 0; i < rankingList.length; i++) {
    newRank = 'rank' + i;

    if (typeof ranks[newRank] !== 'undefined') {
        // skip
        continue;
    } else {
        ranking = '<div id="' + newRank + '" ...';
    }

    ranks[newRank] = newRank;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...