簡體   English   中英

每個()的jQuery選擇器僅迭代當前級別?

[英]JQuery selector for each() to iterate through only the current level?

今天出現了瑣碎的問題。

我正在使用JQuery解析XML文件。 它包含一棵樹,其中包含幾個稱為<property> ,其中包含<option>元素。 他們定義了下拉菜單。 這是一個例子:

<property>
    <option>
        <text>option 1</text>
    </option>
    <option>
        <text>option 2</text>
    </option>
    <option>
        <text>option 3</text>
    </option>
</property>

這很容易解析,但是有時另一個<property>嵌套在<option>因為它定義了一個子菜單,該子菜單僅在選擇了給定選項時才出現:

<property>
    <option>
        <text>option 1</text>
    </option>
    <option>
        <text>option 2</text>
        <property>
            <option>
                <text>suboption 1</t
            </option>
            <option>
                <text>suboption 2</text>
            </option>
        </property>
    </option>
    <option>
        <text>option 3</text>
    </option>
</property>

這些嵌套的<property>元素可能包含更多的<property>元素,依此類推。 基本上,它是一個樹形結構。

問題是我如何才能使用jQuery從給定級別收集<option>元素。 如果我這樣做

$(xml).find('property').each(function () {
    var selector = $('<select></select>', {'id': $(this).attr('id')});
    $(this).find('option').each(function () {
        $(selector).append($('<option></option>', {'text': $(this).find('text').text()}));
    });
    $('#controls').append(selector);
});

...它將收集當前級別和所有更低級別的所有<option>元素。 因為我將當前級別稱為$(this)所以我不知道如何告訴JQuery僅從當前級別( $(this)級別)收集它們,而只留下較低級別。 有人可以解決我的jQuery知識方面的空白嗎? 謝謝。

編輯:我意識到我的評論看起來更像在回答。 哎呀 :)

考慮使用jQuery的.children()方法替代.find() 這樣,您將僅遍歷直接后代。

function generateSelectElementFromXml(xml) {
  var selector = $('<select></select>', {'id': $(this).attr('id')});
  $(xml).children('property').each(function () {
    $(this).children('option').each(function () {
        $(selector).append($('<option></option>', {
          'text': $(this).children('text').text()
        }
      ));
    });
  });
  return selector;
}

然后,您可以在控件<div>生成一個<select>元素,如下所示:

$('#controls').append(generateSelectElementFromXml(xml));

這是CodePen的示例: http ://codepen.io/anon/pen/NAYQAV

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM