Find and style individual elements of HTML through their index in jQuery

点点圈 提交于 2020-08-10 13:04:07

问题


I am working on a party game (i.e. Tambola/Housie) where I want to automatically identify all the numbers on each ticket that have been called out on the housie board. For example: if 86 has been called out then I want to highlight it (i.e. change its font color or background color) on ticket no. 2 and 3 respectively. The problem is the tickets are getting displayed on the page as an html as it has been copied from another webpage where they are getting created. So, I want a solution which can find these numbers and then color them individually. Any help will be greatly appreciated.

These tables are the ones which are below "current nos." in the image. These tables are nothing but tambola tickets. The nos. in these tables are random numbers and get generated with the help of a function. These numbers are not in my control. What I want to achieve is whenever a number is called by the host i.e. in our example they will be 1,3,45,46,48,49,50,86,87,90, I want to check whether these nos. are present in each of the tickets. If yes, then change the font color or background color of those numbers in the respective tickets

I have inserted 'space' between each number so that I can find them easily. There is space before and after each number in the table. For example: running $(#tickets).text() will give this output -

  1. 1 32 54 72 81... and so on (refer image).

Some code that I have written to identify the numbers is as follows:

<body>
<div id='tickets' style="font-size: 40px">
            </div>
    
<script>

var array = [];
var num = [1,3,45,46,48,49,50,86,87,90]     //numbers are actually getting picked from local storage
var clonetkt = localStorage.getItem("checktiks");    //cloning tickets as html from another webpage

        

for (i = 1; i <= 90; i++) {
            array.push(i);
 }

 for (a = 0; a <= num.length; a++) {
                for (b = 0; b < 90; b++) {
                    if (array[b] == num[a]) {
                        array[b] = 0;
                    }
                }
            }

function recreatetable() {
            $('#tickets').html(clonetkt);   //displaying ticket tables as html
            
            var z;
            var n;
            if (array[i - 1] == 0) {
            z= " " + i + " ";    //inserting space to match with elements of the ticket
            n = $('#tickets').text();
            $('#tickets').each(function(){    //trying to match elements of the ticket but works only on the first find. will not find more than one occurrence
            n = $('#tickets').text().indexOf(z);
            if (n >=0){
            console.log($('#tickets').text()[n+1] + $('#tickets').text()[n+2]);     //to check whether the number was actually found in #tickets
            }
            });
        }
        }
        recreatetable(0);

</script>
</body>

Please help!

download .js file from here for ticket generation: https://drive.google.com/file/d/1CxmEO1jBOVft6y68BZyuXBAAby7lXwi2/view?usp=drivesdk


回答1:


As you have already store the value of ticket which you need to highlight inside array we can use this only for hightlighting other tickets as well.So, for iterating through every ticket we can use each loop and then we can compare if value of td and the value of array matches or not if yes then add some class i.e : highlight to add css to that particular td.

Demo Code :

var array = [];
var num = [1, 3, 45, 46, 48, 49, 50, 86, 87, 90];
//var clonetkt = localStorage.getItem("checktiks");


for (i = 1; i <= 90; i++) {
  array.push(i);
}

for (a = 0; a <= num.length; a++) {
  for (b = 0; b < 90; b++) {
    if (array[b] == num[a]) {
      array[b] = 0;
    }
  }
}

function recreatetable() {
 // $('#tickets').html(clonetkt); //cloning tickets from another webpage in this div (i.e. 'tickets')

  var boardhtml = "<table border='1'>";
  var z;
  var n = [];
  for (i = 1; i <= 90; i++) {
    if (i == 1 || i == 11 || i == 21 || i == 31 || i == 41 || i == 51 || i == 61 || i == 71 || i == 81) {

      boardhtml += "<tr>"; //creating housie board at top
    }
    if (array[i - 1] == 0) {
      boardhtml += "<td bgcolor='lightgreen' id='td" + i + "'><font color='red'>" + i + "</font></td>";

    } else {
      boardhtml += "<td id='td" + i + "'>" + i + "</font></td>";
    }

    if (i == 10 || i == 20 || i == 30 || i == 40 || i == 50 || i == 60 || i == 70 || i == 80 || i == 90) {
      boardhtml += "</tr>";
    }
  }
  boardhtml += "</table>";
  document.getElementById('board').innerHTML = boardhtml;

}
recreatetable(0);
add_color(); //call this hightlight tickets

function add_color() {
  for (i = 1; i <= 90; i++) {
    if (array[i - 1] == 0) {
      z = " " + i + " ";
      //loop through table trs
      $('#tickets table tr').each(function() {
      //find td
        $(this).find('td').each(function() {
        //check if text inside td and the value z is equal
          if ($(this).text() == z) {
          //add class
            $(this).addClass('highlight')
            
          }//close if
        })//close loop
      })//close loop

    }//close if

  }//for close
}//close function
.highlight {
  background-color: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housiebd">
  <h1>
    <center> HOUSIE BOARD </center>
  </h1>
  <table id="hboard" style="margin: 20px auto;">
    <tr>
      <td id="board" style="text-align: center; font-size: 32px;">
      </td>
    </tr>
  </table>
</div>
<br>
<center>
  <div id='cnos' style="font-size: 20px">
    Current Nos.: 1, 3, 45, 46, 48, 49, 50, 86, 87, 90
  </div>
</center><br>

<center>
  <div id="div" style="font-size: 24px;
margin: 20px auto;
padding: 10px;
text-align: center;">
  </div>
</center>
<!--demo tickets-->
<div id="tickets">
  <table id="tiktable0" style="border: 1px solid black; margin: 20px auto; width: 500px; height: 250px;">
    <thead>
      <tr>
        <th colspan="9">1. Ajparag</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td style="border: 1px solid black;"> 2 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 39 </td>
        <td style="border: 1px solid black;"> 42 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 69 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 84 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"> 5 </td>
        <td style="border: 1px solid black;"> 16 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 56 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 75 </td>
        <td style="border: 1px solid black;"> 86 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 17 </td>
        <td style="border: 1px solid black;"> 29 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 48 </td>
        <td style="border: 1px solid black;"> 57 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 87 </td>
      </tr>
    </tbody>
  </table>
  <table id="tiktable1" style="border: 1px solid black; margin: 20px auto; width: 500px; height: 250px;">
    <thead>
      <tr>
        <th colspan="9">2. Apj</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td style="border: 1px solid black;"> 6 </td>
        <td style="border: 1px solid black;"> 11 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 41 </td>
        <td style="border: 1px solid black;"> 52 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 84 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"> 8 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 37 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 53 </td>
        <td style="border: 1px solid black;"> 65 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 86 </td>
      </tr>
      <tr>
        <td style="border: 1px solid black;"> 9 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 28 </td>
        <td style="border: 1px solid black;"> 38 </td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"></td>
        <td style="border: 1px solid black;"> 73 </td>
        <td style="border: 1px solid black;"> 89 </td>
      </tr>
    </tbody>
  </table>
</div>



回答2:


I would use two separate loops instead of wrapping two loops into another which is way less performant. Creating the <tr> can also be simplified by using the modulo operator as shown here. Please note that I could not use LocalStorage variables as their contents were not described in your code; adapt your code as required to this answer.

I would also recommend to get rid of deprecated elements like <center> and use CSS classes instead (e.g. td { text-align: center; }).

var clonetkt = '1 6 8 11 43 59'; //localStorage.getItem("checktiks");
let $tickets = $('#tickets');

function highlightMatches() {
  let matches = $tickets.html().split(' ');
  for (let match of matches) {
    $('#td' + match).addClass('highlight');
  }
}

function recreateTable() {
  $tickets.html(clonetkt); //cloning tickets from another webpage in this div (i.e. 'tickets')

  var boardhtml = "<table border='1'>";
  for (let i = 1; i <= 90; i++) {
    if (i % 10 === 1) {
      boardhtml += "<tr>"; //creating housie board at top
    }

    boardhtml += "<td id='td" + i + "'>" + i + "</font></td>";

    if (i % 10 === 0) {
      boardhtml += "</tr>";
    }
  }
  boardhtml += "</table>";
  document.getElementById('board').innerHTML = boardhtml;

  highlightMatches();

  /*
  var prenoary = JSON.parse(localStorage.getItem("previousNos"));
  $('#pnos').append(prenoary + "  ");
  var crrtnoary = JSON.parse(localStorage.getItem("currentNos"));
  $('#cnos').append(crrtnoary + "  ");
  */
}

recreateTable();
body {
  font-family: 'Open Sans', sans-serif;
}
.highlight {
  background: green;
  color: white;
}

h1,
td,
div.info {
  text-align: center;
}

#hboard {
  margin: 20px auto;
}

#hboard #board {
  text-align: center;
  font-size: 32px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housiebd">
  <h1>
    HOUSIE BOARD
  </h1>
  <table id="hboard">
    <tr>
      <td id="board">
      </td>
    </tr>
  </table>
</div>

<div class="info">
  <div id='pnos' style="font-size: 40px">
    Previous Nos.:
  </div>
</div>

<div class="info">
  <div id='cnos' style="font-size: 40px">
    Current Nos.:
  </div>
</div>

<div class="info">
  <div id='tickets' style="font-size: 40px">
  </div>
</div>


来源:https://stackoverflow.com/questions/63008362/find-and-style-individual-elements-of-html-through-their-index-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!