jQuery checkbox .prop() problem
I have a function that worked perfectly well before upgrading to jQuery 1.6.2, but now won't work at all. In the past, the function used .attr("checked") , but I've tried switching to .prop("checked") instead. I have been pulling my hair out trying to figure out why I cant get .prop("checked") to return a value.
The function is suposed to hide the actual checkboxes and add or remove a class to the parent li based on the state of the checkbox. Two things that worked before, no longer work.
HTML :
<ul class="checkboxes">
<li><input type="checkbox" name="boro[]" value="Bronx">Bronx</li>
<li><input type="checkbox" name="boro[]" value="Brooklyn" checked>Brooklyn</li>
<li><input type="checkbox" name="boro[]" value="Queens">Queens</li>
</ul>
jQuery:
$('ul.checkboxes').checkBoxes();
$.fn.checkBoxes=function() {
$ul=$(this);
$ul.addClass("checkboxes").find("input:checkbox").hide();
$ul.find("li").addClass($(this).find("input:checkbox").prop("checked")?"checked":"unchecked").click(function(e) {
$(this).toggleClass("checked unchecked").find("input:checkbox").att("checked",!$(this).prop("checked"));
)}
)};
Thanks for any insight!
You have a few errors:
1) You need to define your function checkBoxes
before calling it.
2) Not really an error, but there is no point saying addClass('checkboxes') when you've already added that class in HTML.
3) $(this).find("input:checkbox").prop("checked")
This will only determine if the first checkbox is checked or not. I'm almost positive you want $(this) to refer to the current checkbox, but it's not in the right scope.
4) You wrote att
instead of attr
5) You have an extra )
at the end of your function.
Here is code that I believe does what you want:
$.fn.checkBoxes = function() {
$(this)
.addClass("checkboxes")
.find("input:checkbox")
.hide()
.end() -- revert back to $(this)
.find("li")
.each(function(){
$(this).addClass(
$(this)
.find("input:checkbox")
.prop("checked") ? "checked" : "unchecked"
);
})
.click(function(e) {
var $cb = $(this)
.toggleClass("checked unchecked")
.find("input:checkbox");
$cb.attr("checked", !$cb.prop("checked"));
});
};
$('ul.checkboxes').checkBoxes();
http://jsfiddle.net/cpvQ4/
如果您的问题只是您发布的代码中的语法错误,请尝试以下操作(语法错误已更正):
$.fn.checkBoxes=function() {
$ul=$(this);
$ul.addClass("checkboxes")
.find("input:checkbox")
.hide();
$ul.find("li")
.addClass($(this).find("input:checkbox").prop("checked")?"checked":"unchecked")
.click(function(e) {
$(this)
.toggleClass("checked unchecked")
.find("input:checkbox")
.attr("checked",!$(this).prop("checked"));
});
};
$('ul.checkboxes').checkBoxes();
链接地址: http://www.djcxy.com/p/4730.html
上一篇: jQuery数据vs Attr?
下一篇: jQuery复选框.prop()问题