打开并用标签包装li元素

unwrap and wrap a li element with a tag

本文关键字:包装 li 元素 标签      更新时间:2023-09-26

我试图用一个标记包装两个列表元素。默认情况下,只有一个列表再次具有标记。当单击该元素时,我想从单击的元素中删除a标记,并将其添加到其他列出的元素中。然后,当第二个元素将被点击时,做同样的事情。我使用了以下两个函数,如果它们在不同的html文档中,但当我将它们放在一起时,它们会起作用。只有一个有效。有什么帮助吗?

var pTags = $( "#ab" );
var pTags1 = $("#cd");
$( "#xx" ).click(function()
{
if ( pTags1.parent().is( "a" ) ) 
{
pTags1.unwrap();
pTags.wrap( "<a href='#' id='xv'></a>" );
}
});
$( "#xv" ).click(function()
{
if ( pTags.parent().is( "a" ) ) 
{
pTags.unwrap();
pTags1.wrap( "<a href='#' id='xx'></a>" );
}
});
</script>

<!doctype html>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>unwrap demo</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
    type="text/javascript"></script>
</head>
<body>
<li id="ab">Hello</li>
<a href="#" id="xx"><li id="cd">cruel</li></a>
</body>
<script>
var pTags = $( "#ab" );
var pTags1 = $("#cd");
$( "#xx" ).click(function()
{
if ( pTags1.parent().is( "a" ) ) 
{
pTags1.unwrap();
pTags.wrap( "<a href='#' id='xv'></a>" );
}
});
$( "#xv" ).click(function()
{
if ( pTags.parent().is( "a" ) ) 
{
pTags.unwrap();
pTags1.wrap( "<a href='#' id='xx'></a>" );
}
});
</script>
</html>

首先您的html无效li应该是ulol的直接子级。

你需要使用on事件处理程序,因为当第二个元素被包装时,点击事件不会附加到它上

<span id="ab">Hello</span>
<a href="#" class="clickable" id="xx"><span id="cd">cruel</span></a>
<script>
    $(document).ready(function () {
        $(document).on('click', 'a.clickable', function () {
            var id = $(this).attr('id');
            $('span', this).unwrap();
            if (id == 'xx') {
                $('#ab').wrap("<a href='#' class='clickable' id='xv'></a>");
            }
            else if (id == 'xv')
                $('#cd').wrap("<a href='#' class='clickable' id='xx'></a>");
        });
    });
</script>

这只是一个样本,如果你清楚自己想做什么,还有更好的方法吗?