开发者

Javascript putting a if statement inside append(' ')?

Alrighty so below I have this script doing exactly what I want; I'm using it to add background fadeIn/fadeOut using jquery for my navigation bar.

With my design I have a separator image at the end of each li in a ul for my nav bar; to add that in I'm putting the span in with class "sep" which contains my css to add the separator image as a background in the proper location.

Now my problem is that I have the separator being a background image aligned right so it occurs at the right of each nav item (see below for a text-based example of its structure) and I wish the final item of the navigation to not have the separator.

Current Example Structure: ( Item 1 | Item 2 | Item 3 | )

What I want it to be: ( Item 1 | Item 2 | Item 3 )

Now to do this inside the javascript I would somehow nee开发者_运维技巧d to eliminate the entire "<span class="sep"></span>" or just the "class="sep"" ONLY on my last li nav item (its ID is #n7)

So I'm assuming a general way to do it would be to add a if statement that if the current li ID is NOT #n7 (my li ID's go from #n1 to #n7, #n7 being the final) then it puts in "<span class="sep"></span>" so if it was #n7 it would not include it

Any help would be great, thanks.

Javascript Code:

$(document).ready(function () {

 //Append a div with hover class to all the LI
 $('#nav li').append('<div class="hover"><span class="sep"></span></div>');



 $('#nav li').hover(

  //Mouseover, fadeIn the hidden hover class 
  function() {

   $(this).children('div').fadeIn('1000'); 

  }, 

  //Mouseout, fadeOut the hover class
  function() {

   $(this).children('div').fadeOut('1000'); 

 }).click (function () {

  //Add selected class if user clicked on it
  $(this).addClass('selected');

 });

});


You can use the :last-child pseudo-class to select the last child and :not() to select all but that. Also > to not go down multiple levels but only look at immediate children.

$('#nav > li:not(:last-child)').append('<div class="hover"><span class="sep"></span></div>');
$('#nav > li:last-child').append('<div class="hover"></div>');

This is a standard CSS selector; in jQuery it will always work but as a CSS selector it would not work in any current release of IE.


$('#nav li').each(function() {
   var append_separator = (this != $('#nav li:last')[0]);
   $(this).append('<div class="hover">' + ((append_separator) ? '<span class="sep"></span>' : '') + '</div>')
});

jsFiddle example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜