我在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 的"这个",它对我不起作用。我想让链接的网址 我附加评论系统.如何查找和实现此 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>');
如果您有多个'.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>');
});
你可以通过做这样的事情来获取 href
var href=$('.embed a').attr('href');
尝试如下:
$('.embed').find('a').attr('href');
而不是this
只使用$('.embed a').attr('href')
你可以在这里看到: JS 小提琴
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>'
});