I'm trying to build a script that counts the number of characters in an anchor tag inside a list item and, if the number of characters is higher than 18, makes the anchor tag narrower so that the text will break. Here's what I have so far, but it's not working. Help?
$('nav li a').each(function() {
var curr = this.text().length();
if(c开发者_运维技巧urr >= 18){
this.width(50);
}
});
Oh, and for bonus points: is there some way to make the text on the second line indent after the anchor shrinks?
try this instead:
$('nav li a').each(function() {
var curr = $(this).text().length;
if(curr >= 18){
$(this).width(50);
}
});
I notice you're missing a character from your nav selector - either a . or a #
For your second point about indenting the second line, try this:
#nav li a {
display: block;
margin-left: 15px;
text-indent: -15px;
}
You've got a few little glitches here.
- You have to do everything after the page loads, so something like $(document).ready(...) would be necessary.
- The each function doesn't work quite like you had it, it takes two parameters that you can then work with.
- And lastly, the anchor tag is
an inline tag, so it has no width.
For what you want to work you'd need
to either style your a tags with
display: block
ordisplay: inline-block
, or just use a different container.
So this would work with the text directly in the list item for example:
$(document).ready(function(){
$('li').each(function(index, listItem) {
var curr = $(listItem).text().length;
if(curr >= 18){
$(listItem).width(50);
}
});
});
Just a shot in the dark:
You probably didn't set the anchor's display to block
or inline-block
.
Alternatively, you've got a particularly long word, which will not break automatically unless you add some <wbr>
s. Quirksmode has a nice page about wordbreaks
精彩评论