如何在jQuery中使用自定义属性名选择最接近的属性



嗨,请看我下面的html代码

<tr> .....</tr>
<tr>
<td data-colname="ctv">hello</td>
<td class="my_t">Yes</td>
<td class="mybutton">Click here</td>
</tr>
<tr> .....</tr>

我可以使用

在自定义函数中选择my_t值
$(".mybutton").on("click",function(){
$(this).closest("tr").find(".my_t").css("color","red");
});

it is working fine.

但是下面的代码不工作。如何选择data-colname="ctv";* *在吗?

$(".mybutton").on("click",function(){
$(this).closest("tr").find("[data-colname='ctv']").css("color","green");
});

请帮

编辑添加了一个带有上述代码的代码片段

$(".mybutton").on("click", function() {
$(this).closest("tr").find(".my_t").css("color", "red");
});
$(".mybutton").on("click", function() {
$(this).closest("tr").find("[data-colname='ctv']").css("color", "green");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td data-colname="ctv">hello</td>
<td class="my_t">Yes</td>
<td class="mybutton">Click here</td>
</tr>
</table>

实际上,您提供的代码没有选择,因为它没有包含在<table>元素中。请试试这个:

var res = $(".my_t").parent().find("[data-colname='ctv']");
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr> .....</tr>
<tr>
<td data-colname="ctv">hello</td>
<td class="my_t">Yes</td>
</tr>
<tr> .....</tr>
</table>

处理这个HTML结构的解决方案之一:

$(".mybutton").on("click",function(){
$(this).parents("tr").find("td[data-colname='ctv']")[0].css("color","green");
});

最新更新