[英]Get href of div
我在div中有一個鏈接:
<div class="embed">
<a href="http://google.com/"></a>
</div>
所以現在我想附加Facebook評論系統:
$('.embed a').append('<div class="fb-comments" data-href="' + this + '" data-num-posts="1" data-width="470"></div>');
如您所見,我的href帶有“ this”,它對我不起作用。 我想在附加評論系統的鏈接上添加URL。 如何找到並實施此網址? 示例: JsFiddle
this is not available in this context
您必須自己使用該元素$('.embed a').attr('href')
$('.embed a').append('<div class="fb-comments" data-href="' + $('.embed a').attr('href') + '" data-num-posts="1" data-width="470"></div>');
您可以通過執行以下操作來獲取href
var href=$('.embed a').attr('href');
如果您有多個'.embed a'
,則需要對其進行操作並提供正確的href:
$('.embed a').each(function(){
$(this).append('<div class="fb-comments" data-href="' + $(this).attr('href') + '" data-num-posts="1" data-width="470"></div>');
});
嘗試如下:
$('.embed').find('a').attr('href');
而不是this
只是使用$('.embed a').attr('href')
您可以在這里看到: JS Fiddle
您可以在html
函數的上下文中使用html
方法, this
是指您的錨鏈接。
$('.embed a').html(function(i, c){
return '<div class="fb-comments" data-href="' + this.href + '" data-num-posts="1" data-width="470"></div>'
});
如果要附加/添加html標記,並且元素具有html內容,則可以串聯html內容:
$('.embed a').html(function(i, current){
return current + '<div class="fb-comments" data-href="' + this.href + '" data-num-posts="1" data-width="470"></div>'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.