jquery - get an html attribute from within a function call
I'm trying to call a different tooltip according to an anchor tag's id attribute. My JavaScript code is as follows:
$(function()
{
$('.tippy').qtip(
{
content: {
url: "http://mydomain.com/product/mini/" + $(this).attr("id") // doesn't work
},
hide: { when: 'mouseout', fixed: true },
position: {
corner: {
target: 'bottomRight',
tooltip: 'topLeft'
开发者_运维技巧 }
}
});
});
my html code looks like this:
<div>this is the text and I would like to reference the <a href="product.php" class="tippy" id="123456">superproduct</a> with qtip.</div>
I'm pretty stuck, could you give me a hand please?
Use each()
:
$('.tippy').each(function() {
$(this).qtip({
content: {
url: "http://mydomain.com/product/mini/" + $(this).attr("id")
},
hide: { when: 'mouseout', fixed: true },
position: {
corner: {
target: 'bottomRight',
tooltip: 'topLeft'
}
}
});
)};
The reason why $(this)
does not work in your code is simple: It is not inside a function call (at least not where this
should refer to a .tippy
element). $(this).attr()
is executed when you construct the object that is passed to qtip()
. That means it is in the same context as $('.tippy')
and therefore this
most probably refers to window
.
精彩评论