[英]unwrap and wrap a li element with a tag
我試圖用標簽包裝兩個列表元素。 默認情況下,只有一個列表再次具有標簽。 單擊該元素后,我想從單擊的元素中刪除一個標簽,然后將其添加到其他列出的元素中。 然后,當第二個元素被單擊時,執行相同的操作。 我使用了以下兩個功能,如果它們在不同的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
應該是ul
或ol
的直接子代。
您需要使用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>
這只是一個示例,如果您清楚自己想做什么,還有更好的方法嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.