how can i use jquery delegate() properly to toggleclass?
i'm new to jquery, so forgive me my misunderstandings. i use this code:
$(".redbox").delegate("input开发者_运维百科[type=checkbox]", "change", function(){
var index = this.id.substring(8);
$(".inputfield" + index).toggleClass("complete");
});
to toggle a class on the input of a input textfield. At first this code worked fine, but since i append the whole thing with jquery, delegate() makes all checkboxes and inputfields toggle.
you can see what i mean in this code: http://jsfiddle.net/eD5M5/
click me ---> appends the append button append button ----> appends checkbox and input field (+remove button)
when you click append once the toggle class seem to look fine! but when you click more than once and start to toggle, everything toggles!
My question to you is;
What am i doing wrong, and how can i fix this?
Thanks in advance
They all are given the same class, and you're selecting them by class, so it will affect them all.
Instead of selecting by class, just use .next()
to traverse from the checkbox to the text field.
Example: http://jsfiddle.net/eD5M5/3/
$(this).next().toggleClass("complete");
This is because you are not incrementing the counter, so all inputs have the same class: check the fix
精彩评论