简体   繁体   English

打开并包装带标签的li元素

[英]unwrap and wrap a li element with a tag

I'm trying to wrap two list elements with an a tag. 我试图用标签包装两个列表元素。 By default only one list again has the a tag. 默认情况下,只有一个列表再次具有标签。 When that element is clicked I want to remove the a tag from the clicked element the add it the other listed element. 单击该元素后,我想从单击的元素中删除一个标签,然后将其添加到其他列出的元素中。 Then when the second element will be clicked do the same thing. 然后,当第二个元素被单击时,执行相同的操作。 I used these follwoing two functiosn that work if they are in different html document but when I put them together. 我使用了以下两个功能,如果它们在不同的html文档中,但是当我将它们放在一起时,它们可以工作。 Only one works. 只有一件作品。 Any help? 有什么帮助吗?

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>

first off your html is invalid li should be a direct child of a ul or ol . 首先,您的html无效, li应该是ulol的直接子代。

u need to use the on event handler becuase when the second element is wrapped the click event won't attach to it. 您需要使用on事件处理程序,因为第二个元素被包装时,click事件不会附加到该事件处理程序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>

this is just a sample and there are better ways of doing it, if you be clear about what you want to do ? 这只是一个示例,如果您清楚自己想做什么,还有更好的方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM