Jquery, accessing data from a click within a function
-
09-06-2021 - |
Question
I have this jquery code:
$('.viewmap').click(function () {
updateMap();
});
So when someone clicks a link with the viewmap class it runs a function called updateMap. In the updateMap function I create a variable like so:
var mapid = $(this).attr('title');
The variable above does not work, it has a undefined value, my question is in the viewmap click function how do I access the current data via $(this) in the updateMap function?
Solution
pass a reference of this
to the updateMap function
$('.viewmap').click(function () {
updateMap(this);
});
function updateMap(obj) {
var mapid = $(obj).attr('title');
...
}
OTHER TIPS
one alternative is to add a parameter to updateMap and call updateMap($(this)); instead of updateMap();
There is two recomended ways:
//If u don't want to do any work before the updateMap call
$('.viewmap').click(updateMap);
//If u want do do anything before updateMap call
$('.viewmap').click(function(e) {
updateMap.apply(this, arguments);
});
Both ways will pass the this and every new argument jquery add now and in the future
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow