本文介绍了使用JQuery构建锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用jquery来构建HTML,如下所示:
I want to use jquery to build HTML like this:
<li><a href="#"><span class="play"></span><span class="trackName">Track Name</span></a></li>
这看起来很简单,但是我不知道如何将HTML标签作为锚文本的一部分.
It seems simple but I can't figure it out how to include HTML tags as part of my anchor text.
如果我使用类似的东西:
If I use something like:
$("<a />", { text: $('<SPAN class="play" />') + "Track Name" })
然后使span标签转义.
then the span tags get escaped.
推荐答案
有几种方法可以做到这一点,包括(但不限于):
There are several ways to do it, including (but not limited to):
// one big string
$('<a href="#"><span class="play"></span><span class="trackName">Track Name</span></a>')
// create <a> then append() the span
$('<a></a>').attr("href","#")
.append('<span class="play"></span><span class="trackName">Track Name</span>');
// create <a> then set all of its contents with html()
$('<a></a>').attr("href","#")
.html('<span class="play"></span><span class="trackName">Track Name</span>');
// append spans created earlier:
var spans = $('<span class="play"></span><span class="trackName">Track Name</span>');
var a = $('<a></a>').append(spans);
请注意,.html()
会替换所有现有内容,而.append()
会添加到末尾.因此,假设您的示例中有两个span元素,则可以独立创建它们,并一次附加一个:
Note that .html()
replaces any and all existing contents, while .append()
adds to the end. So given that you have two span elements in your example you could create those independently and append them one at a time:
$('<a href="#"></a>').append('<span class="play"></span>')
.append('<span class="trackName">Track Name</span>');
这篇关于使用JQuery构建锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!