问题
I am trying to make the background color change for each checked item in a row in a while loop. Currently the jQuery only works on the last row. I did put an $i
variable in the input id, but to be honest, I'm not sure what to do beyond it. I tried this, the .each
function, and a bunch of answers on Stack Overflow, but I can't figure out how to take care of this.
Here is the jQuery:
$(document).ready(function(){
$('#org[$i]').change(function(){
if(this.checked){
$(this).siblings('table').removeClass('unchecked');
$(this).siblings('table').addClass('checked');
$(this).parentsUntil('td').removeClass('unchecked');
$(this).parentsUntil('td').addClass('checked');
} else {
$(this).siblings('table').removeClass('checked');
$(this).siblings('table').addClass('unchecked');
$(this).parentsUntil('td').removeClass('checked');
$(this).parentsUntil('td').addClass('unchecked');
}
});
});
Here is the loop (with some unimportant stuff cut out). $i
iterates properly in each #org
(I checked in Firebug):
if ($i % 4 == 0) echo ($i > 0? '</tr>' : '') . '<tr>';
echo "<td class=\"unchecked\">
<div class=\"unchecked\">
<input id=\"org[".$i."]\" style=\"float:right\" type=\"checkbox\" name=\"org\" value=\"".$row['i_id']."\"/>
<table class=\"unchecked\">
//blah, blah, blah
</table>
</div>
</td>';
if ($i == $countRows - 1)
echo '</tr>';
$i++;
回答1:
Your problem is that you're trying to match an id like org[1]
as output by PHP, but you're using a jQuery selector with [$i]
in it - that doesn't work, for a few reasons.
What will work is a jQuery selector like this:
$('input[id^="org\["]')
This will select input elements with an id
that starts with org[
. I placed a backspace in front of the bracket because jQuery has a special meaning for brackets, and this "escapes" that special meaning.
回答2:
Why don't you just use CSS for this?
input[type="checkbox"] + label {
// Whatever you want to do
}
input[type="checkbox"]:checked + label {
// Whatever you want to do.
}
here is a simple fiddle showing this off.
回答3:
In you javascript you use $i but it is pp variable. Actually you can use class not ids for this purpose
<?php foreach($items as $item){ echo '<input type="checkbox" ..something else... class="dummy" />';}
In javascript
$('.dummy').change(function(e){ //Do something that you need});
来源:https://stackoverflow.com/questions/18793532/jquery-only-affects-the-last-result-in-a-while-loop-mysql