简体   繁体   中英

javascript foreach and jquery's .append()

I've wasted an entire day trying to work it out, and I think I nailed it, but still not sure what the heck :/

I have a js file, where I generate <option> 's for a <select> :

_htmlString = '<option value="' + __hex_value + '" data-class="' + _cbtn.substring(1, 13) + '">' + __hex_value + '</option>\n';  
jQuery("#colourtiles").append(_htmlString);

#colourtiles is an ID of a <select> . I also have 3 static options in that select, inside html.

Now, in another script I'm doing this:

        [].slice.call( this.el.children ).forEach( function(el) {
        console.info(el);
        if( el.disabled ) { return; }

        var tag = el.tagName.toLowerCase();

        if( tag === 'option' ) {
            options += createOptionHTML(el);
        }
        else if( tag === 'optgroup' ) {
            options += '<li class="cs-optgroup"><span>' + el.label + '</span><ul>';
            [].slice.call( el.children ).forEach( function(opt) {
                options += createOptionHTML(opt);
            } )
            options += '</ul></li>';
        }
    } );

...but this only renders 3 elements, completely ignoring these added by .append(). And to be clear, when I return that <select> in console, it's all there. But I've noticed, that this.el.children.length is ...3!

So it looks like 1) jQuery isn't updating .length, and 2) forEach() relies on it, therefore failing. I'm I correct? Is it a bug in jQuery, or am I being stupid? How do I resolve this?

Many thanks in advance for all the answers. Marcin

First, I would append each option like this

 $("<option/>")
    .val(__hex_value)
    .data("class",_cbtn.substring(1, 13))
    .html(__hex_value)
    .appendTo("#colourtiles");

I don't know what el is in your code so I can't really give more of an answer on this, but if you want to loop through each option in that select, use .each() and it will include what you did in the DOM:

$("option","#colourtiles").each(function(i,v){
  ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM