Reputation: 9081
I have read this tutorial tuto
i'd like to use the attribut data-
in a hypertext link:
<a href="#" onClick="openbox2('Validation de concept technique', 1)" data-arr="@fa.Id_element" id="lien">Donner votre avis</a>
in the javascript part:
function openbox2(formtitle, fadin) {
var self = $(this);
var arr = self.data('arr');
alert(arr);
}
i get always the same alert message undefined
.
What is the reason of this problem? How can i fix it?
Upvotes: 1
Views: 68
Reputation: 388316
Since you are using inlined click handler, this
inside the handler function does not refer tot he clicked element, you need to pass the reference as a parameter to the handler method
<a href="#" onClick="openbox2(this, 'Validation de concept technique', 1)" data-arr="@fa.Id_element" id="lien">Donner votre avis</a>
then
function openbox2(el, formtitle, fadin) {
var self = $(el);
var arr = self.data('arr');
alert(arr);
}
Demo: Fiddle
Another solution is to pass a custom context to the openbox2
method using .call()
<a href="#" onClick="openbox2.call(this, 'Validation de concept technique', 1)" data-arr="@fa.Id_element" id="lien">Donner votre avis</a>
then
function openbox2(formtitle, fadin) {
var self = $(this);
var arr = self.data('arr');
alert(arr);
}
Demo: Fiddle
Upvotes: 2
Reputation: 337590
Due to the way you have attached your event, this
is not the element which was clicked on. Using on-
event attributes is very outdated now, and is not a good separation of concerns. As such it should be avoided. As you are already using jQuery for your logic it's best to also use it to attach your events:
<a href="#" data-arr="@fa.Id_element" id="lien" class="openbox">Donner votre avis</a>
$('.openbox').click(openbox2);
function openbox2(formtitle, fadin) {
var self = $(this);
var arr = self.data('arr');
alert(arr);
}
Upvotes: 3