Assign function to row
I have the following function that changes row color based on a particular selection. it works fine if there's only one row.
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>
however, if I add more rows, they all get the same color... clearly i need to differentiate th开发者_运维技巧em somehow...
<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>
Instead of using the selector again, use 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.
You need to implement loop for going through all the mySelectors
I don't see where the .relationship
element is in you HTML. Do you mean to bind the change
event to .mySelector
? If so, this would solve it:
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));
});
Basically, you need to pass a reference to the element that has changed as an argument to the myFunc()
function.
You can use $(this), like:
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);
});
精彩评论