I have a jquery code
$(function() {
$("input").on("mouseover", function() {
var a = $('input').attr('name');
populate(a);
});
});
I have three input elements.
Computer Language: <br>
<div>
<datalist id="language"></datalist>
<input type="text" list="language" name= "language" id="search"/>
</div>
<br>
Country: <br>
<div>
<datalist id="country"></datalist>
<input type="text" list="country" name= "country" id="search" />
</div>
<br>
Degree: <br>
<div>
<datalist id="degree"></datalist>
<input type="text" list="degree" name= "degree" id="search"/>
</div>
Now, mouseover
event only fires that have name language
(or the top input element). Why mouseover
event is not being fired for 2nd and 3rd input elements?
Note: The id
s are not meant to be duplicated. You have used id="search"
many times.
You need to use the context-sensitive this
keyword:
$(function() {
$("input").on("mouseover", function() {
var a = $(this).attr('name');
populate(a);
});
});
To answer your question:
The reason being, you are executing the .attr()
( which is one of many functions that processes only one element ) on the first matched element.
You need to refer to the current element which is done using $(this)
, this
refer to the element that invokes the event. $(this)
will return the object. While $('input').attr('name')
will refer to the first input
element
var a = $(this).attr('name');
You could use the parameter of your handler:
$("input").on("mouseover", function(e) {
var a = $(e.target).attr('name');
populate(a);
});
e.target is exatcly the element you are looking for.
You can use directly javascript instead to transform the element into a jQuery object:
$("input").on("mouseover", function(e) {
var a = e.target.getAttribute('name');
populate(a);
});
In JQuery code you always get "language" input
, because it is first input
in dom , as your code search first input
.
Change your jQuery code as below:
$(function () {
$("input").on("mouseover", function () {
var a = $(this).attr('name');
populate(a);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.