I'm trying to iterate through all the empty textboxes in a table and change its background colour. I'm using the following JQuery code:
$("#btn2").click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
emptyTextBoxes.each(function() {
this.css('background-color', '#ffff00');
// $('#Col3Txtbx').css开发者_Go百科('background-color', '#ffff00');
});
});
This
does not seem to refer to the textbox which seems strange to me. When I uncomment out the particular textbox, it does reset the background colour.
Can someone explain to me what 'This' is referring to?
The each function works a little differently:
$("#btn2").click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
emptyTextBoxes.each(function(index, element) {
$(element).css('background-color', '#ffff00');
});
});
But you can make this work without each() as well:
$("#btn2").click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
emptyTextBoxes.css('background-color', '#ffff00');
});
Even shorter version:
$("#btn2").click(function() {
$("input:text[value='']").css('background-color', '#ffff00');
});
Edit: as "rz" pointed out, you can still use the this
keyword, but you'll have to wrap the element into a jQuery object:
$("#btn2").click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
emptyTextBoxes.each(function() {
$(this).css('background-color', '#ffff00');
});
});
As per the docs, the callback to each will be passed an index and the element in question and this will be set to the domElement. So, change this.css('background-color', '#ffff00')
to $(this).css('background-color', '#ffff00');
the this that is changing the color is referring to the button. If you move this where you return this.value it might work.
精彩评论