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. 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
.
u need to use the on
event handler becuase when the second element is wrapped the click event won't attach to it.
<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 ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.