我有以下HTML元素结构:
<span class="parent">
<span class="keyword">belal</span>
<span class="string"> "Belal Mostafa"</span>
</span>
现在我想动态选择.parent
类并将其子节重构为:
<span class="parent">
<span class="keyword">belal</span>
<span class="string"> "Belal </span>
<span class="string"> Mostafa"</span>
</span>
我在考虑以下情况,但仍然无法完成:
答案 0 :(得分:2)
你可以循环每个.parent
,在每个字符串的循环之后循环并分割所有空格并将结果附加到父级。
示例
$(".parent .string").each(function(){
if($(this).text().trim().indexOf(" ") != -1)
{
var parent = $(this).parents(".parent");
$.each($(this).text().trim().split(" "),function(index,value){
parent.append("<span class='string'>"+value+"</span>");
});
$(this).remove();
}
});
.string{
border:solid 1px #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="parent">
<span class="keyword">belal</span>
<span class="string"> "Belal Mostafa Test"</span>
</span>
答案 1 :(得分:1)
您可以使用jQuery append
var text = $(".string").text().trim(); //getting text of string element
$(".string").remove(); //removing existing
text.split(" ").forEach(function(item){ //splitting it to append span elements
$(".parent").append("<span class='string'>" + item + "</span>"); //appending to parent element
});
&#13;
.string{
border: 1px solid blue; /*just for view, remove it later*/
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="parent">
<span class="keyword">belal</span>
<span class="string"> "Belal Mostafa"</span>
</span>
&#13;