I'm creating script that will add , at every unordered list's list element with exception for the last list element - it should end with ;. This should happen for each unordered list!
It's like...
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
<ul>
<li>d</li>
<li>e</li>
<li>f</li>
</ul>
...to:
<ul>
<li>a,</li>
<li>b,</li>
<li>c;</li>
</ul>
<ul>
<li>d,</li>
<li>e,</li>
<li>f;</li>
</ul>
My code looks like this at the moment...
$('ul').each(function(i) {
var listsLength = $(this + 'li').length;
$(this + 'li').each(function(j) {
if (i == (listsLength - 1)) {
$(开发者_开发百科this).append(';');
} else {
$(this).append(',');
}
});
}
I think that problem is this code...
$( this + 'li' )
Any idea how to get the same effect?
Edit:
Fixed it. There was actually syntax error as well and also I used i where j should be placed. Now all works and here's the outcome.
Edit #2:
Just use @lonesomeday code... it's much readable and lightweight!
You can't do this + 'li'
. this
, in this context, is a DOM element, not a string. To get the effect you want, you'd need $(this).find('li')
.
Your loop is also unnecessary. You can do something far better with :last-child
:
$('ul li:last-child').append(';');
$('ul li:not(:last-child)').append(',');
Those two lines will have the effect you want.
Instead of $( this + 'li' )
do $( 'li', this )
this + 'li'
will try to convert this
to a string, and then concat 'li'
to it.
Try this instead:
$('li', this)
You could use
$(this).find ('>li').each(...)
instead (if the problem is really here).
精彩评论