我有一个包含4个元素的表单,这里是一个:
<form class="frm">
<div class="first-field">
<input class="text1" type="text" placeholder="Uw naam.." value="">
<svg version="1.1" class="unfilled" id="svg_user"></svg>
</div>
我得到了以下jQuery代码:
$(function(){
$('.text1').keyup(function(){
if ($(this).val() == '') { //Check to see if there is any text entered
//If there is no text within the input then add default class 'unfilled'
$("#svg_user").attr("class", "unfilled");
} else {
/*If there is text in the input, then change default
class 'unfilled' to new class 'filled'.*/
$("#svg_user").attr("class", "unfilled filled");
}
});
});
它检查输入元素是否已填充,并根据函数的结果将类应用于内部SVG元素。这很好用。
但是我有4个输入元素并且为了使它工作,我需要为每个输入元素提供一个不同的类,并使用上面的jQuery代码4次来工作。
必须有更快更清洁的方法来做到这一点吗?
答案 0 :(得分:0)
您可以使用公共类
<div class="first-field">
<input class="text1 required" type="text" placeholder="Uw naam.." value="" />
<svg version="1.1" class="unfilled svg_user"></svg>
</div>
然后
$('.required').keyup(function () {
var $svg = $(this).next();
if ($(this).val() == '') {
$svg.attr("class", "unfilled");
} else {
$svg.attr("class", "unfilled filled");
}
});
演示:Fiddle