I have a ul
:
<ul>
<li>1</li>
<li><a href="#">2</a></li>
</ul>
I need a thing that I want to make first li to anchor means
<li>1</li>
to
<li><a href="#">1</li></li>`
and remove anchor from 2开发者_开发问答nd means
<li><a href="#">2</a></li> to <li>2</li>
How can I do this in jQuery?
Very simple method, that "toggles" the links:
$('ul li').each(function() {
if($(this).find('a').length > 0) {
$(this).text($(this).text());
}
else {
$(this).html($('<a />').attr('href', '#').text($(this).text()));
}
});
Example: http://jsfiddle.net/E2ryt/
Update:
From your comment I think you want this:
$('ul li').each(function() {
$(this).html($('<a />').attr('href', '#').text($(this).text()));
}).click(function() {
$(this).text($(this).text());
});
But I'm not 100% sure. See here: http://jsfiddle.net/E2ryt/1/
Update 2:
Based on David's comment, you might want this:
var lastClicked = null;
$('ul li').click(function() {
if(lastClicked) {
lastClicked.html($('<a />').attr('href', '#').text(lastClicked.text()));
}
lastClicked = $(this).text($(this).text());
});
See here: http://jsfiddle.net/E2ryt/2/
精彩评论