为了账号安全,请及时绑定邮箱和手机立即绑定

如何检查 html 表中的 hasClass

如何检查 html 表中的 hasClass

弑天下 2023-12-11 16:49:47
当我创建表格时,我想hasClass通过单击相应的单元格(单元格上方)来检查每个元素是否我的工作如下。但效果并不好。我怎样才能实现它?以及什么是错误点?谢谢$("td.number").click(function(){  id=$(this).index();  $("td.color").index(id).hasClass("aqua");  });td {  transition-duration: 0.5s;  border: solid black 1px;  padding: 5px;}.number{cursor:pointer;}table {  border-collapse: collapse;}.color{ padding:5px; } .aqua {  background-color: aqua;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id=calendar></div><script>let html = ''html += '<table>';let i = 0;html += '<tr>';for (let d = 0; d < 15; d++) {  i = i + 1;  html += '<td class="number">' + i +'</td>'}html += '</tr>';for (let w = 0; w < 1; w++) {  html += '<tr>';  for (let d = 0; d < 15; d++) {    html += '<td class="color"></td>'    }    html += '</tr>';  }html += '</table>'document.querySelector('#calendar').innerHTML = html;const arr = [1, 2, 10, 11, 14];$("td.color")  .filter(function() { return arr.includes($(this).index()+1); })  .addClass('aqua');</script>
查看完整描述

2 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

.index()用于以整数形式返回位置,而不是根据其索引查找元素 - 对于您想要的.eq()


更新的小提琴:


$("td.number").click(function(){

  id=$(this).index();

  $(this).toggleClass("aqua", $("td.color").eq(id).hasClass("aqua"));

});

td {

  transition-duration: 0.5s;

  border: solid black 1px;

  padding: 5px;

}


.number{

cursor:pointer;}


table {

  border-collapse: collapse;

}


.color{

 padding:5px;

 }

 

.aqua {

  background-color: aqua;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id=calendar></div>


<script>

let html = ''

html += '<table>';

let i = 0;


html += '<tr>';

for (let d = 0; d < 15; d++) {

  i = i + 1;

  html += '<td class="number">' + i +'</td>'

}

html += '</tr>';


for (let w = 0; w < 1; w++) {

  html += '<tr>';

  for (let d = 0; d < 15; d++) {

    html += '<td class="color"></td>'

    }

    html += '</tr>';

  }

html += '</table>'

document.querySelector('#calendar').innerHTML = html;


const arr = [1, 2, 10, 11, 14];


$("td.color")

  .filter(function() { return arr.includes($(this).index()+1); })

  .addClass('aqua');

</script>


查看完整回答
反对 回复 2023-12-11
?
当年话下

TA贡献1890条经验 获得超9个赞

您需要通过使用eq()而不是index()访问您需要的元素来更改选择器:


$("td.number").click(function(){

  var id = $ (this).index();

  $("td.color").eq(id).hasClass("aqua");

});


查看完整回答
反对 回复 2023-12-11
  • 2 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信