Добавьте событие mouseenter ко всем входам с именем в массиве, используя jquery - PullRequest
0 голосов
/ 11 октября 2018

Я не знаю, как вызывать мою функцию для всего ввода с именем, которое содержит мой массив.Я пробовал это:

var names = ["name1", "name2"];
$(document).ready(function(){
  $('input[name=names[0]').on("mouseenter", function() {
     $(this).attr('title', 'This is the hover-over text');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Head</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<input type="text" name="name1"> <!--This should have title-->
<input type="text" name="name2"> <!--This should have title-->
<input type="text" name="name3"> <!--This should not have title--

Я пытался получить первый элемент там, но я не могу сделать даже это.Я очень новичок в jquery (и js тоже), поэтому решение может быть очевидным.

Ответы [ 5 ]

0 голосов
/ 11 октября 2018

Вы можете сделать что-то вроде этого:

var names = ["name1", "name2"];

//Iterate over all the text box inputs in your HTML
document.querySelectorAll('[type=text]').forEach(function(el) {
  //Check if el name attribute is in the array
  if (names.indexOf(el.name) > -1) {
    //If so, add a change event listener
    el.addEventListener('keyup', function(e) {
      //Set the title attribute to something new
      updateTitle(el, e);
    });
  }
});

function updateTitle(el, e) {
  el.title = e.target.value;
  console.log(`Updated ${el.name}: title attribute changed to ${el.title}`);
}
<h2>Head</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<input type="text" name="name1">
<!--This should have title-->
<input type="text" name="name2">
<!--This should have title-->
<input type="text" name="name3">
<!--This should not have title-->
0 голосов
/ 11 октября 2018

Ваша проблема, похоже, в том, как вы используете селектор.Это не читается как часть массива, а как строка.

$(document).ready(function(){
    var names = ["name1", "name2"];
    
    // interpolation
    $(`input[name=${names[0]}]`).on("mouseenter", function() {
         $(this).attr('title', 'This is the hover-over text');
    });
    
    // or without interpolation
    $('input[name=' + names[1] + ']').on("mouseenter", function() {
         $(this).attr('title', 'This is different hover-over text');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name1" />
<input type="text" name="name2" />
0 голосов
/ 11 октября 2018

Попробуйте это:

$("input[name^='name'").on("mouseenter", function() {
...

Ссылка URL: https://api.jquery.com/attribute-starts-with-selector/

0 голосов
/ 11 октября 2018

Используйте .filter() для фильтрации селектора jquery и добавления к ним прослушивателя событий.

var names = ["name1", "name2"];
$("input").filter(function(){
  return names.indexOf($(this).attr("name")) != -1;
}).on("mouseenter", function() {
  $(this).attr('title', 'This is the hover-over text');
});

var names = ["name1", "name2"];
$("input").filter(function(){
  return names.indexOf($(this).attr("name")) != -1;
}).on("mouseenter", function() {
  $(this).attr('title', 'This is the hover-over text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name1" value="name1">
<input type="text" name="name2" value="name2">
<input type="text" name="name3" value="name3">

Также вы можете добавить прослушиватель событий ко всем входам и в функции обратного вызова проверить его имя.

var names = ["name1", "name2"];
$("input").on("mouseenter", function() {
  if (names.indexOf($(this).attr("name")) != -1){
    $(this).attr('title', 'This is the hover-over text');
  }
});

var names = ["name1", "name2"];
$("input").on("mouseenter", function() {
  if (names.indexOf($(this).attr("name")) != -1){
    $(this).attr('title', 'This is the hover-over text');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name1" value="name1">
<input type="text" name="name2" value="name2">
<input type="text" name="name3" value="name3">
0 голосов
/ 11 октября 2018

Вы просто запускаете цикл над массивом и добавляете eventlistner для каждого элемента массива, который содержит имя inpput.

$(document).ready(function(){
     $.each(names , function(index, item) {
       $("input[name="+ item +"]").on("mouseenter", function() {
         $(this).attr('title', 'This is the hover-over text');

   });
 });
});
...