我的<ul>
列表包含<a>
个链接。我想找到<li>
WITHOUT <a>
并将<a>
打包到其中。
如何检查<li>
是否没有<a>
(在这种情况下为<li>hello</li>
)?
<ul class="sorter">
<li>
<a href="url">blabla</a>
</li>
<li>
hello
</li>
</ul>
答案 0 :(得分:6)
$(document).ready(function()
{
$("ul.sorter li:not(:has('a'))").each(function()
{
$(this).append('<a href="#">added</a>');
});
});
更新使用<li>
打包<a>
文字:
$(document).ready(function()
{
$("ul.sorter li:not(:has('a'))").each(function()
{
$(this).html('<a href="#">' + $(this).text() + '</a>');
});
});
答案 1 :(得分:1)
$(".sorter li").each(function(){
var li = $(this)
var a_tag = li.find('a');
//without <a> tag
if( a_tag.length == 0 ){
//keep content in <li>
var li_txt = li.html();
//add <a> tag
li.html('<a href="#">' + li_txt + '</a>');
}
});
小提琴
答案 2 :(得分:1)
您可以使用JQuery。
在html的头部添加以下行
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
然后在身体的末尾添加以下
<script>
$( document ).ready(function() {
$('body ul').find('li').each(function(){
var isA = $(this).find('a');
if(isA.length == 0){
$(this).append('<a href="#">Lorem Ipsum</a>');
}
});
});
</script>