【发布时间】:2019-04-09 18:26:07
【问题描述】:
我试图在单击第一个元素时引用第二个元素,但它不起作用。我尝试了几种不同的方法,但都不起作用。
$(function(){
$('#firstName').on('blur', function(e){
// I tried to get the closest first name to the input
var $firstNameLabel = $(e.target).closest('.firstName');
if (e.target.value.trim() === '') {
$firstNameLabel.addClass('error');
} else {
$firstNameLabel.removeClass('error');
}
});
$('#lastName').on('blur', function(e){
// I also tried to use the parent get the closest last name to the input
var $lastNameLabel = $(e.target).closest('.form-group .lastName');
if (e.target.value.trim() === '') {
$lastNameLabel.addClass('error');
} else {
$lastNameLabel.removeClass('error');
}
});
});
.form-group label { display: inline-block; min-width: 80px; }
.error { color: rgb(240, 0, 0); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="firstName" class="firstName">First Name:</label>
<input type="text" name="firstName" value="" id="firstName">
</div>
<div class="form-group">
<label for="lastName" class="lastName">Last Name:</label>
<input type="text" name="lastName" value="" id="lastName">
</div>
【问题讨论】:
标签: jquery