我有以下功能可根据特定选择更改行颜色。如果只有一行,它可以正常工作。
function myFunc() {
var opt = $(".mySelector").val();
if (opt == "left") {
$(".mySelector").closest("tr").find("td").css("background-color","red");
} else if (opt == "right") {
$(".mySelector").closest("tr").find("td").css("background-color","green");
}
}
$(".mySelector").change(function(){
myFunc();
});
myFunc();
<table>
<tr>
<td>val 1</td>
<td>val 2</td>
<td>
<select class="mySelector">
<option value="left">red</option>
<option value="right">green</option>
</select>
</td>
</tr>
</table>
然而,如果我添加更多行,它们都会得到相同的颜色......显然我需要以某种方式区分它们......
<table>
<tr>
<td>val 1</td>
<td>val 2</td>
<td>
<select class="mySelector">
<option value="left">red</option>
<option value="right">green</option>
</select>
</td>
</tr>
<tr>
<td>val 3</td>
<td>val 4</td>
<td>
<select class="mySelector">
<option value="left">red</option>
<option value="right">green</option>
</select>
</td>
</tr>
</table>
答案 0 :(得分:1)
不要再使用选择器,而是使用this
。
function myFunc() {
var opt = $(this).val();
if (opt == "left") {
$(this).closest("tr").find("td").css("background-color","red");
} else if (opt == "right") {
$(this).closest("tr").find("td").css("background-color","green");
}
}
$(".mySelector").change(myFunc).change(); //Call change twice. The first will add the callback and the second will trigger a change event on each .mySelector element.
答案 1 :(得分:0)
您需要实现循环以遍历所有mySelectors
答案 2 :(得分:0)
我看不到HTML中.relationship
元素的位置。您的意思是将change
事件绑定到.mySelector
吗?如果是这样,这将解决它:
function myFunc($this) {
var opt = $this.val();
if (opt == "left") {
$this.closest("tr").find("td").css("background-color","red");
} else if (opt == "right") {
$this.closest("tr").find("td").css("background-color","green");
}
}
$(".mySelector").change(function(){
myFunc($(this));
});
基本上,您需要将对已更改的元素的引用作为参数传递给myFunc()
函数。
答案 3 :(得分:0)
您可以使用$(this),例如:
function myFunc($obj) {
var opt = $obj;
if (opt == "left") {
$(".mySelector").closest("tr").find("td").css("background-color","red");
} else if (opt == "right") {
$(".mySelector").closest("tr").find("td").css("background-color","green");
}
}
$(".mySelector").change(function(){
myFunc($obj);
});