在jQuery中在锚点内添加span标签

5
如何在锚点内添加span标签,将其从原来的状态更改为:
<a href="somewhere.html">Here is the link to somewhere.</a>

用jQuery实现这个。
<a href="somewhere.html">
<span>Here is the span content.</span>
Here is the link to somewhere.
</a>

在jQuery文档中查找html()函数并使用它来更改锚点内容。 - pawelmysior
3个回答

8

试试这个:

$('a').each(function() {
     $(this).prepend('<span>This is the span content</span>');
});

这将在页面上的每个a元素的开头添加一个标签。如果您想将修改限制为某些特定元素,请为它们添加一个类,并使用类似于$('a.myclass').each(...的方式调用它们。


@marcgg,您错了,请在投票之前查看手册中prepend的文档。 - Tatu Ulmanen
是的,我的错,我在你发表评论的几秒钟前意识到了。我立刻取消了我的反对票。 - marcgg

4
也许这会起作用:
$('a').each(function()
{
  $(this).wrapInner("<span></span>");
});

JQuery docs


2

增加一种选择链接的方式:

<a id="myLink" href="somewhere.html">Here is the link to somewhere.</a>

做一些jQuery:

var $link = jQuery("#myLink");
$link.html( "<span>blah</span>" + $link.html() );

使用prepend是一个更酷的方法:
jQuery("#myLink").prepend("<span>blah</span>");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接