我有以下一段html(在cms环境中):
<div id="languageswitch">
<div class="language-object">
<span class="Language selected" title="English (United States)">
</span>
<span class="Language" title="Nederlands (Nederland)">
<a href="http://mylocalwebsite.nl/nl-nl/">
</a>
</span>
</div>
</div>
所以我想获得每种语言的span标题,并将其插入并将其包含在带有类文本的另一个span中。 HTML结果应如下所示:
<div id="languageswitch">
<div class="language-object">
<span class="Language selected" title="English (United States)">
<span class="text">Eng</span>
</span>
<span class="Language" title="Nederlands (Nederland)">
<a href="http://mylocalwebsite.nl/nl-nl/">
<span class="text">Ned</span>
</a>
</span>
</div>
</div>
到目前为止,我的解决方案无法正常工作,因为两种语言的文本相同而不是两种:
//get the span.Language title
var getLanguageTitle = $('#languageswitch').children("div").children("span").attr("title");
//insert new spans to show the span titles
$('#languageswitch span').each(function () {
$(this).append("<span class='text'></span>");
});
$('span.text').append(getLanguageTitle);
我的jsfiddle是:http://jsfiddle.net/7tjb1fw7/1/
答案 0 :(得分:2)
你过度复杂的事情:
$('.Language').each(function () {
var txt = $(this).attr('title');
$(this).append("<span class='text'>" + txt + "</span>");
});
修改:如果要查看链接,可以执行以下操作:
$('.Language').each(function () {
var txt = "<span class='text'>" + $(this).attr('title') + "</span>",
link = $('a', this);
if(link.length){ link.append(txt); }
else { $(this).append(txt); }
});
答案 1 :(得分:1)
要获得您想要的确切结果,请尝试以下方法:
$('#languageswitch span.Language').each(function () {
// fetch first 3 letters of the language:
var lang = $.trim($(this).attr("title")).slice(0,3);
var a = $(this).find('a');
// check if the span contains anchor element:
if(a.length){
// if so, update html of the link
a.html("<span class='text'>"+lang+"</span>");
}else{
// if not, append span:
$(this).append("<span class='text'>"+lang+"</span>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="languageswitch">
<div class="language-object">
<span class="Language selected" title="English (United States)">
</span>
<span class="Language" title="Nederlands (Nederland)">
<a href="http://mylocalwebsite.nl/nl-nl/">
</a>
</span>
</div>
</div>