Reputation: 11240
I'm creating a little dynamic tooltip function.
Basically if I have a link like so:
<a href="#" data="xyz">?</a>
Using qTip, I attempt to lookup a tooltip table in mysql and retrieve the tip based on the data in the data attribute.
So:
$('a[data]').qtip({
content: {
url: '/tooltip.php',
data: { tipKey: $(this).attr('data') },
method: 'post'
}
});
Problem is, it doesn't work. $(this).attr('data') doesn't seem to pull the value inside the attribute.
If I manually change the function so it looks like the following it works no problem.
$('a[data]').qtip({
content: {
url: '/tooltip.php',
data: { tipKey: 'xyz' },
method: 'post'
}
});
What am I missing when I'm trying to pull the data from the data attribute? Should I be doing something like:
$('a[data]').qtip({
content: {
url: '/tooltip.php',
data: { tipKey: ''+$(this).attr('data')+'' },
method: 'post'
}
});
As that isn't yielding the value either!
Upvotes: 1
Views: 975
Reputation: 11509
You should try accessing the 0th element of data. Like this:
data: { tipKey: $("a[data]")[0].data},
EDIT: oh ok, i see, this should work then as an alternative.
Upvotes: 1
Reputation: 827238
Your code doesn't works because the this
keyword represents the context of the function that is being executed, and you are using it inside an object literal.
For example, if you execute your snippet in the $(document).ready
event, the this
keyword will represent the document element.
You could iterate over your selector and initialize each element tooltip individually:
$('a[data]').each(function () {
var $link = $(this);
$link.qtip({
content: {
url: '/tooltip.php',
data: { tipKey: $link.attr('data') },
method: 'post'
}
});
});
Also note that the data
attribute is not standard, your page will not pass the W3C Validator.
Upvotes: 4
Reputation: 625027
This example works for me:
<html>
<head>
<title>Text</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
alert($("a[data]").text());
});
</script>
</head>
<body>
<a href="#" data="123">abc</a>
</body>
</html>
Upvotes: 1