gpt4 book ai didi

jquery - 在不复制代码的情况下扩展 jQuery 函数

转载 作者:行者123 更新时间:2023-11-28 05:05:39 25 4
gpt4 key购买 nike

下面的脚本用于隐藏段落,直到 div.form 中的所有文本字段都已填写。

就像现在一样,为了显示段落,我必须填写两个表格。我想要的是让每种形式独立行动。换句话说,如果您在第一个表单中填写了三个输入,第一个 DIV 中的段落就会显示出来。

我可以通过复制代码并添加更多类来完成此操作,但这显然不太理想。

HTML

<div class="form one">  
<input type="text" />
<input type="text" />
<input type="text" />
<p style="display:none">All inputs in this DIV contain text</p>
</div>

<div class="form two">
<input type="text" />
<input type="text" />
<input type="text" />
<p style="display:none">All inputs in this DIV contain text</p>
</div>

jQuery

$('.form input').keyup(function() {

var empty = false;
$('.form input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});

if (empty) {
$('.form p').css('display', 'none');
} else {
$('.form p').css('display', 'block');
}
});

最佳答案

您只需从 .form 中选择 inputp:

$('.form input').keyup(function() {

var empty = false,
$form = $(this).parent();

$form.find('input').each(function() {
if ($(this).val() == '') {
empty = true;
return false; // stops the loop
}
});

if (empty) {
$form.find('p').css('display', 'none');
} else {
$form.find('p').css('display', 'block');
}
});

这是 fiddle :http://jsfiddle.net/tGBGK/

附言您可以通过缓存选择器来进一步优化这一点。


或者,您可以放弃循环,只使用属性选择器:

$('.form input').keyup(function() {

var $form = $(this).parent(),
empty = $form.find('input[value=]').length;

if (empty) {
$form.find('p').css('display', 'none');
} else {
$form.find('p').css('display', 'block');
}
});

...这是 fiddle :http://jsfiddle.net/tGBGK/1/


您可以使用三元运算符进一步缩短它:

$('.form input').keyup(function() {

var $form = $(this).parent(),
empty = $form.find('input[value=]').length;

$form.find('p').css('display', empty ? 'none' : 'block');
});

...最后,这是 fiddle :http://jsfiddle.net/tGBGK/2/

谢谢@JesseB。

关于jquery - 在不复制代码的情况下扩展 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8207610/

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