问题
I am trying to use the jQuery qTip plugin to display the text inside the element.
I have multiple links in a table like so with different classes. The text in the links is hidden with a negative text indent and a background sprite is used to make them look unique.
<a href="#" class="spot_quote">Spot quote</a>
<a href="#" class="contract_quote">Contract quote</a>
I thought this would jquery would just pick up the text in the link:
$('.contract_quote, .spot_quote').qtip(
{
content: $(this).text() // Give it some content, in this case a simple string
});
But it returns way more than i need or want. I don't really want to add the title attribute as it is not needed here.
回答1:
JavaScript has no block-level scope. That means that your this
refers to the document. In order for this
to refer to each element, you need to create a new function:
$(document).ready(function() {
$('.contract_quote .spot_quote').each(function() {
$(this).qtip({
content: $(this).text();
});
});
});
That said, even if you'd need the title attribute, it would be good practice to set it anyway. Setting it automatically with JavaScript is OK but not ideal. Setting it with your CMS (if you use one) would be better. If a user agent, for some reason, is looking for the title of the link, it's just better to have one, even if it's always the same as the content, as user agents are not as smart as humans. Most of the times, anyway.
来源:https://stackoverflow.com/questions/3290685/qtip-jquery-plugin-to-display-text-from-link