Edit: Okay, I had to redo the example because the problem didn't occur in my first example
function Check开发者_运维知识库boxClick(checkbox, check) {
this.checked = check;
checkbox.click(function (event) {
alert(this.checked);
});
}
CheckboxClick($("#checkbox"), $("#checkbox").attr("checked"));
Every time you click on that checkbox, this.checked's value changes. What do I need to do to get it to stop changing? It's obviously assigning by reference but I don't know how to get the primitive value. I tried valueOf() but that didn't work for me.
By primitive I think you mean the value in the html source.
Use jquery 1.6, it has a new prop()
method and changed the meaning of attr()
to return what is the value of the attribute in the html source.
http://api.jquery.com/attr/
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.
http://api.jquery.com/prop/
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
Ahhh the issue is that this
isn't what you maybe expecting. this
actually refers to the checkbox that triggered the event (DOM element not jquery). So when you use this.checked
that is the equivalent of the jquery statment $("#checkbox").attr("checked")
which is why it changed when you clicked.
I just changed this.checked to var checked and it works.
Note: If you're using jQuery 1.6 and above, you'll also have to change .attr method to .prop, with the same parameters.
精彩评论