jQuery: How to assign a variable inside of .html
I have written some jQuery to get a value and then store it in a variable no problem:
$(document).ready(function(){
$('a.news_video_player_list').click(function () {开发者_运维百科
var youtube = $(this).attr('id');
$('.news_vid_playerL').html('youtube');
});
});
Now that I have the variable "youtube", I'd like to put some HTML inside a div named ".news_vid_playerL" with the variable value. My goal was to do this:
$('a.news_video_player_list').click(function () {
var youtube = $(this).attr('id');
$('.news_vid_playerL').html('<iframe title="YouTube video player" width="610" height="420" src="http://www.youtube.com/embed/+youtube+?&rel=0" frameborder="0" allowfullscreen></iframe>');
});
If you look in the src path, you'll see I put a placeholder +youtube+ which I'd like to populate with the variable value. Not sure how to pull that off.
Thanks!
String concatenation:
$(document).ready(function(){
$('a.news_video_player_list').click(function () {
$('.news_vid_playerL').html('<iframe title="YouTube video player" width="610" height="420" src="http://www.youtube.com/embed/'+$(this).attr('id')+'?&rel=0" frameborder="0" allowfullscreen></iframe>');
});
});
You just need to pull the variable out of the string. To do this, you put the first part of the string, then append the variable, and then append the rest of the string, like so:
$('a.news_video_player_list').click(function () {
var youtube = $(this).attr('id');
$('.news_vid_playerL').html('<iframe title="YouTube video player" width="610" height="420" src="http://www.youtube.com/embed/' + youtube + '?&rel=0" frameborder="0" allowfullscreen></iframe>');
});
Otherwise, JavaScript just thinks you want to put "+youtube+" in the URL, rather than the value of the youtube variable.
Ummm like this:
'<iframe title="YouTube video player" width="610" height="420" src="http://www.youtube.com/embed/' + youtube + '?&rel=0" frameborder="0" allowfullscreen></iframe>'
Note the ' + youtube + ' part (the single quote before and after the + signs).
You were close. You're actually including the string +youtube+ in your src. You need to concatinate it into the string like so:
$('a.news_video_player_list').click(function () {
var youtube = $(this).attr('id');
$('.news_vid_playerL').html('<iframe title="YouTube video player" width="610" height="420" src="http://www.youtube.com/embed/'+youtube+'?&rel=0" frameborder="0" allowfullscreen></iframe>');
});
$('.news_vid_playerL').html('<iframe title="YouTube video player" width="610" height="420" src="http://www.youtube.com/embed/' + youtube '?&rel=0" frameborder="0" allowfullscreen></iframe>');
$('a.news_video_player_list').click(function () {
var youtube = $(this).attr('id');
$('.news_vid_playerL').html('<iframe title="YouTube video player" width="610" height="420" src="http://www.youtube.com/embed/"+youtube+"?&rel=0" frameborder="0" allowfullscreen></iframe>');
});
Just cut your quotes, insert your variable and then continue.
精彩评论