我有以下一段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/
最佳答案
要获得所需的确切结果,请尝试以下操作:
$('#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>