0

我浪费了一整天的时间来解决这个问题,我想我做到了,但仍然不确定到底是什么:/

我有一个 js 文件,在其中<option>为 a生成<select>

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

#colourtiles是 a 的 ID <select>。我在该选择中也有 3 个静态选项,在 html 中。

现在,在另一个脚本中,我正在这样做:

        [].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>';
        }
    } );

...但这仅呈现 3 个元素,完全忽略了 .append() 添加的这些元素。需要明确的是,当我<select>在控制台中返回它时,它就在那里。但我注意到,那this.el.children.length是...3!

所以看起来 1) jQuery 没有更新 .length,并且 2) forEach() 依赖于它,因此失败了。我说的对吗?这是jQuery中的错误,还是我很愚蠢?我该如何解决这个问题?

非常感谢您的所有答案。马尔钦

4

1 回答 1

0

首先,我会像这样附加每个选项

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

我不知道el您的代码中有什么,因此我无法对此给出更多答案,但是如果您想遍历该选择中的每个选项,请使用.each()它,它将包括您在 DOM 中所做的事情:

$("option","#colourtiles").each(function(i,v){
  ...
});
于 2014-08-25T02:32:38.870 回答