How do I use jQuery to use the hyperlink text as a variable?
I've got a jQuery function that is going to replace each hyperlink with a jPlayer using that hyperlink as its source. The hyperlink looks like this in HTML:
<div>
<a href="demos/myfile.mp3" rel = 'jPlayer'>myfile</a>
</div>
So what I've got so far in my Javascript is this:
$(document).ready(function() {
$('a[rel="jPlayer"]').jPlayer("setMedia", { mp3: $(this).attr("href") });
});
The problem is I can't figure out the right selector to take the value 开发者_如何转开发of the existing hyperlink and use it for the mp3: source in the code. Maybe I'm not even using $this right, or maybe it's something completely different that I'm missing.
When I run the code as is, I get "a.attributes is null" in Firebug. Can anyone help fix this up?
The thing is with your script construction:
$('a[rel="jPlayer"]').jPlayer("setMedia", { mp3: $(this).attr("href") });
You are referrring with this to jPlayer, not selected value. You should use it in other way, try this:
$('a[rel="jPlayer"]').jPlayer("setMedia", { mp3: $('a[rel="jPlayer"]').attr("href") });
or eaven
var anchor = $('a[rel="jPlayer"]');
anchor.jPlayer("setMedia", { mp3: anchor.attr("href") });
There can be more than one link on the page. To correctly initialize each jPlayer instance you can iterate over all links and initialize jPlayer for each matched element.
$(document).ready(function() {
$('a[rel="jPlayer"]').each(function(index){
var link = $(this);
link.jPlayer("setMedia", { mp3: link.attr("href") });
});
});
If this
isn't working in an obvious manner, I'd pull out the selector and re-use it.
$(document).ready(function() {
var media_link = $('a[rel=jPlayer]');
media_link.jPlayer("setMedia", { mp3: media_link.attr("href") });
});
This has the dual effect of only calling extend
on the anchor element once rather than twice. I changed the selector slightly by removing the quote marks.
精彩评论