gpt4 book ai didi

javascript - jQuery:获取相关或接近的元素?

转载 作者:行者123 更新时间:2023-11-30 13:41:40 25 4
gpt4 key购买 nike

我的 HTML 代码:

<p><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
}
});

该怎么做?请帮我解决这个问题。非常感谢!

最佳答案

你可以这样做:

$("input.txt").focus() {
$("label[for='" + this.id + "']").addClass("highlight");
}).blur(function() {
$("label[for='" + this.id + "']").removeClass("highlight");
});

与:

label.highlight { background: yellow; font-weight: bold; }

当输入字段获得焦点时,它的标签(假设它有一个)会突出显示。

编辑:遍历输入并对标签做一些事情:

$(":input[id]").each(function() {
if ($(this).val() != '') {
$("label[for='" + this.id + "'").each(do_something);
}
});

function do_something() {
// this refers to the label
}

或者简单地说:

$(":input[id]").each(function() {
if ($(this).val() != '') {
$("label[for='" + this.id + "'").addClass("notnull");
}
});

或者你可以走另一条路:

$("label[for]").each(function() {
var label = this;
$("#" + $(this).attr("foo") + ":input").each(function() {
if ($(this).val() != "") {
$(label).addClass("notnull");
}
});
});

关于javascript - jQuery:获取相关或接近的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2011428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com