Как я могу удалить повторение в этом коде? - PullRequest
2 голосов
/ 27 сентября 2019

Я просто вызываю функцию highlightInput(this), которая просто меняет цвета для выбранного ввода.Я думаю, что может быть лучший способ избежать повторения.Есть идеи?

HTML-файл

<div class="form-group">
    <label for="your_name">Your name:</label>
    <input type="text" class="form-control" name="your_name" onfocus="highlightInput(this);">
</div>
<div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" name="email"onfocus="highlightInput(this);">
</div>
<div class="form-group">
    <label for="title">Event title:</label>
    <input type="text" class="form-control" name="title"onfocus="highlightInput(this);">
</div>
<div class="form-group">
    <label for="location">Event location:</label>
    <input type="text" class="form-control" name="location"onfocus="highlightInput(this);">
</div>

Как выглядит highlightInput:

var Color = {
    inputColor:function (color, self){
        $(self).css('backgroundColor', color);
    }
}

function highlightInput(self){
    Color.inputColor('lightyellow', self);
    $(self).blur(function(){
        Color.inputColor('white', self);
    });
}

Ответы [ 3 ]

3 голосов
/ 27 сентября 2019

Избавьтесь от jQuery и сделайте это с помощью CSS.

input.form-control:focus {
 background-color: lightyellow;
}
<input type="text" class="form-control">
1 голос
/ 27 сентября 2019

Вы можете использовать селектор jQuery, чтобы добавитьEventListener.

Добавьте следующее в тег <head>.

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>



JavaScript
$('input.form-control').focus(function(e){
   highlightInput(this);
});
0 голосов
/ 27 сентября 2019

$('input.form-control').blur(function() {
  this.style.backgroundColor = 'white';
});

$('input.form-control').focus(function() {
  this.style.backgroundColor = 'lightyellow';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <label for="your_name">Your name:</label>
  <input type="text" class="form-control" name="your_name">
</div>
<div class="form-group">
  <label for="email">Email:</label>
  <input type="email" class="form-control" name="email">
</div>
<div class="form-group">
  <label for="title">Event title:</label>
  <input type="text" class="form-control" name="title">
</div>
<div class="form-group">
  <label for="location">Event location:</label>
  <input type="text" class="form-control" name="location">
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...