gpt4 book ai didi

javascript - 将类添加到包含 Dog 1 及其之间的行的表行

转载 作者:行者123 更新时间:2023-12-01 00:59:35 27 4
gpt4 key购买 nike

代码是自动生成的,所以我无法通过添加 HTML 来添加类/id 等,所以我尝试使用 js 来执行此操作。我 chop 了内容,但基本上我想将类“dog1”添加到与 Dog 1 相关的行,将类“dog2”添加到与 Dog 2 相关的行。

<table>
<tr><td><span>Dog 1 Name</span></td></tr>
<tr><td><span>Dog 1 Age</span></td></tr>
<tr><td><span>Dog 1 Weight</span></td></tr>
<tr><td><span>Date of last appointment</span></td></tr>
<tr><td><span>Dog 1 Number</span></td></tr>
<tr><td><span>Acceptance</span></td></tr>
<tr><td><span>Dog 1 Allergies</span></td></tr>
<tr><td><span>Dog 2 Details</span></td></tr>
<tr><td><span>Dog 2 Name</span></td></tr>
<tr><td><span>Dog 2 Name</span></td></tr>
<tr><td><span>Dog 2 Age</span></td></tr>
<tr><td><span>Dog 2 Weight</span></td></tr>
<tr><td><span>Date of last appointment</span></td></tr>
<tr><td><span>Dog 2 Number</span></td></tr>
<tr><td><span>Acceptance</span></td></tr>
<tr><td><span>Dog 2 Allergies</span></td></tr>
</table>

所以我尝试使用:

$('span:contains("Dog 1").closest('tr').addClass('dog1');

但问题是有些行不包含“Dog 1”(例如:接受、上次约会的日期)

关于如何获取这些内容有什么建议吗?

最佳答案

  1. 在表中查找包含 Dog 1 的跨度的所有 tr。
  2. 对于每一行,如果包含 Dog 1、Dog 2、Dog 3:将类属性设置为“dog1”、“dog2”、“dog3”,...

let dogCounter = 1;
let classAttribute = '';
const $trs = $('span:contains("Dog 1")').first().closest('table').find('tr');

$trs.each((i, tr) => {
const selector = 'span:contains("Dog '+dogCounter+'")';
if ($(tr).find(selector).length) {
classAttribute = 'dog'+dogCounter;
dogCounter++;
}
$(tr).addClass(classAttribute);
})
.dog1 {
color: red;
}
.dog2 {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr><td><span>Dog 1 Name</span></td></tr>
<tr><td><span>Dog 1 Age</span></td></tr>
<tr><td><span>Dog 1 Weight</span></td></tr>
<tr><td><span>Date of last appointment</span></td></tr>
<tr><td><span>Dog 1 Number</span></td></tr>
<tr><td><span>Acceptance</span></td></tr>
<tr><td><span>Dog 1 Allergies</span></td></tr>
<tr><td><span>Dog 2 Details</span></td></tr>
<tr><td><span>Dog 2 Name</span></td></tr>
<tr><td><span>Dog 2 Name</span></td></tr>
<tr><td><span>Dog 2 Age</span></td></tr>
<tr><td><span>Dog 2 Weight</span></td></tr>
<tr><td><span>Date of last appointment</span></td></tr>
<tr><td><span>Dog 2 Number</span></td></tr>
<tr><td><span>Acceptance</span></td></tr>
<tr><td><span>Dog 2 Allergies</span></td></tr>
</table>

关于javascript - 将类添加到包含 Dog 1 及其之间的行的表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56212927/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com