views:

38

answers:

1

To build a menu block which should be switchable with hide/unhide of the menu items, I'm using .append html. The code idea is this:

     navigat += '<h3 class="infoH3"> <a id="' + menuID +'"'
                     + ' href="javascript:slideMenu(\'' + menuSlider + '\');">'
                     +  menuName + '</a></h3>';

     navigat += '<div id="' + menuSlider + '" style="display:none">';
     navigat += '    <ul>';
     navigat += '       <li>aMenu1</li>'
     navigat += '       <li>aMenu2</li>'
     navigat += '       <li>aMenu3</li>'
     navigat += '    </ul>';
     navigat += '<!-- menuName Slider --></div>';
     $("#someElement").append (navigat);

This is doing well .. so far.

But the point is:: I use JS to read the required menu items (eg. 'aMenu1' together with title and/or link info) from a file to build all that, eg. for 'aMenu1' a complex is composed and $("#someElement").append(someString) is used to add that the 'someElement'.

At the moment I build those html elements line by line. Also OK .. as far as the resulting string has the opening and closing tag, eg. "<li>aMenu2</li>".

As can be seen from above posted code there is a line "<div id="' + menuSlider + '" style="display:none">". Appending that -- AFAIS -- the .append is automatically (????) adding "</div>" which closes the statement. That breaks my idea of the whole concept! The menu part isn't included in the 'menuSlider '.

QQ: How to change it -- NOT to have that "</div" added to it??

Günter

A: 

You could change you method around to use document fragment style creation and an object to populate the properties on the elements, like this:

var someElement = $("#someElement");
$('<h3 class="infoH3"></h3>').append($('<a />', 
     { 'id': menuID,
       'href': '#',
       click: function() { slideMenu(menuSlider); }
     })
 ).appendTo(someElement);

var div = $('<div />', { 'id': menuSlider, css: {display: 'none'} });
$('<ul />').append('<li>aMenu1</li>')
           .append('<li>aMenu2</li>')
           .append('<li>aMenu3</li>')
           .appendTo(div);
div.appendTo(someElement);

This is a very different way of doing it, first we're caching the $("#someElement") object so we're not searching for it repeatedly. Then we're creating the <h3> as an object, putting the link inside, then inserting then appending the whole thing to someElement. In the last, the same approach it's creating the <div>, setting it's properties, then creates the <ul> menu and appends it inside...then appends that whole div to someElement as well.

As a side note, I'm not sure how .slideMenu() works, but an event handler that works via $(this).parent().next() (or give the div a class) would work as well, and you wouldn't need a function with the slider argument passed.

Nick Craver