jQuery: Get related or nearly elements?
My codes in HTML:
<p><开发者_StackOverflow社区input type="text" class="txt" id="u" /><label for="u">user</label></p>
<p><input type="text" class="txt" id="p" /><label for="p">pass</label></p>
Javascript:
$(document).ready(function() {
if( $('.txt').val() ) {
//change st in related label tag
}
});
How to do that? Please help me solve this issue. Thank you very much !
You can do:
$("input.txt").focus() {
$("label[for='" + this.id + "']").addClass("highlight");
}).blur(function() {
$("label[for='" + this.id + "']").removeClass("highlight");
});
with:
label.highlight { background: yellow; font-weight: bold; }
While an input field has focus, its label (assuming it has one) is highlighted.
Edit: To traverse the inputs and do something with the labels:
$(":input[id]").each(function() {
if ($(this).val() != '') {
$("label[for='" + this.id + "'").each(do_something);
}
});
function do_something() {
// this refers to the label
}
or simply:
$(":input[id]").each(function() {
if ($(this).val() != '') {
$("label[for='" + this.id + "'").addClass("notnull");
}
});
or you can go the other way:
$("label[for]").each(function() {
var label = this;
$("#" + $(this).attr("foo") + ":input").each(function() {
if ($(this).val() != "") {
$(label).addClass("notnull");
}
});
});
You can look for the labels first and find related text fields, like so:
$('label[for]').each (function ()
{
var label = $(this), textfield = $('#' + label.attr('for') + '.txt');
if (textfield.length && textfield.val ())
doSomething (label);
});
精彩评论