我不知道如何使用数组包含的名称调用所有输入的函数。我已经尝试过:
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)的新手,因此解决方案可能很明显。
最佳答案
使用.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">
关于javascript - 使用jQuery将mouseenter事件添加到数组中具有名称的所有输入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52762350/