[英]How to add a span inside a link tag with jQuery?
我在HTML中有以下代码:
<a class="cta" href="URL" target="_blank">TEXT</a>
我试图实现的目标是在链接标记内添加一个span
标记,使其看起来像这样:
<a class="cta" href="URL" target=_"blank"><span>TEXT</span></a>
我尝试了挂起,但似乎不适用于我的情况…
使用jQuery的.wrapInner( wrappingElement )
:
$(".cta" ).wrapInner("<span></span>");
描述:将HTML结构围绕匹配元素集中的每个元素的内容进行包装。
.wrapInner()
函数可以采用可以传递给$()
工厂函数的任何字符串或对象来指定DOM结构。 该结构可以嵌套在几层深处,但应仅包含一个最里面的元素。 该结构将围绕匹配元素集合中每个元素的内容进行包装。资料来源: https : //api.jquery.com/wrapInner/
.html( function )
是更改元素html内容的好方法。 在函数中的html
变量中设置的元素的当前html内容,您可以在新添加的子元素中对其进行设置。
$("a.cta").html(function(i, html){ return "<span>"+ html +"</span>"; });
span { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="cta" href="URL" target="_blank">TEXT</a> <a class="cta" href="URL" target="_blank">TEXT 2</a>
在jquery中使用.wrapInner()
描述:将HTML结构围绕匹配元素集中的每个元素的内容进行包装。
var con = $('.cta').text();
$(".cta").empty().wrapInner("<span>"+con+"</span>");
您必须先获取内容,然后将其替换为自己制作的内容! 您可以使用$(".myClass")
类的选择器,然后使用$(".myClass").html("<p>My new HTML content</p>");
$(".myClass")
替换文本$(".myClass").html("<p>My new HTML content</p>");
所选目标上的方法:
$(document).ready(function() {
$(".cta").html("<span>" + $(".cta").html() + "</span>");
});
这是一个JSFiddle,可以看到它的实际作用
尝试以下方法:
$('a.cta').each(function(){
var text = $(this).text();//take the text from the link
$(this).html($('<span>',{text:text}));//create a span tag and append the text in it after that use html to append the span to the link tag
});
$('a.cta').each(function(){ var text = $(this).text();//take the text from the link $(this).html($('<span>',{text:text}));//create a span tag and append the text in it after that use html to append the span to the link tag })
span { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="cta" href="URL" target="_blank">TEXT</a> <a class="cta" href="URL" target="_blank">TEXT2</a> <a class="cta" href="URL" target="_blank">TEXT3</a>
替换html()
:
$(function() {
$('.cta').html( '<span>'+$('.cta').html()+</span>' );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.