javascript - 使用 jquery 将 mouseenter 事件添加到数组中具有名称的所有输入

标签 javascript jquery input jquery-selectors

我不知道如何使用我的数组包含的名称对所有输入调用我的函数。我试过了:

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)的初学者,所以解决方案可能很明显。

最佳答案

您只需在数组上运行一个循环并为每个包含输入名称的数组元素添加事件监听器。

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

   });
 });
});

关于javascript - 使用 jquery 将 mouseenter 事件添加到数组中具有名称的所有输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52762350/

相关文章:

Javascript:更改输入值时设置光标位置

c# - 解释 Jint 的工作原理

javascript - 检查 DOM 中隐藏的父元素是否可见

javascript - AngularJS $scope 不会在回调函数中更新吗?

javascript - 在 n 个元素后自动添加行(Jquery)

javascript - Jquery datepicker addclass() 不工作

jquery - 自动调整输入及其邻居输入的问题

c++ - 如何在C++中的二维数组中插入可变数量的数据

javascript - 对象数组与包含对象的对象

javascript - 尽管图层缩放设置等于 [0, 22],Mapbox 样式图层有时会隐藏