如果字段集中有一个 .bad 类的 div,那么禁用按钮的最佳方法是什么?
HTML 示例:
<fieldset>
<div class="item>
<label><span>First Name</span>
<input type="text" name="firstName" placeholder="First" required>
</label>
</div>
<!--adds .bad to parent when input doesn't validate -->
<div class="item bad">
<label><span>Last Name</span>
<input type="text" name="lastName" placeholder="Last" required>
</label>
<!-- .alert only present if doesn't validate -->
<div class="alert">field is required</div>
</div>
<input type="button" class="prev button" value="Previous">
<!-- "disabled" because .bad is present in parent container of Last Name -->
<input type="button" class="next button" value="Next" disabled>
</fieldset>
已修改并应用于此示例的最佳方法和答案:jQuery 示例:
// Bind to the 'change' event of the required input elements
$('input[required]').change(function () {
// cache the value:
var v = this.value;
/* Look for the closest 'div.item',
if the length of the trimmed value is equal to 0 we add 'bad' class,
if it's not 0 we remove the 'bad' class:*/
$(this).closest('div.item')[$.trim(v).length === 0 ? 'addClass' : 'removeClass']('bad');
/* we find the 'input' elements with 'type="button"',
and set their disabled property according to whether,
or not, there's a 'div.bad' contained within the 'fieldset' element: */
$('input[type="button"].next').prop('disabled', function () {
return $(this).closest('fieldset').find('div.bad').length > 0;
});
// We then trigger the 'change' event to disable the buttons if necessary:
}).change();
在这里可以看到大卫的一个工作小提琴:http: //jsfiddle.net/davidThomas/mwkAt/