簡體   English   中英

在jQuery中查找先前同級的子級

[英]Finding child of previous sibling in jQuery

我正在修改現有代碼,因此只能影響存在的元素,而不能正確構建它。 我正在遍歷所有具有類reqd的 spans ,如果是這樣,我將采用直接上一個兄弟姐妹(示例1)或上一個兄弟姐妹的第一個類型輸入的孩子(示例2),並向其添加jQuery validate屬性。

例如,使用prev()就是簡單的#1。 對於示例2和3,我必須使用prevUntil()來更好地隔離我以DOM為目標的位置。

我的問題與示例2有關。 雖然我可以到達class="regfieldlabel我無法讓它遍歷其子級;示例#3與#2相似,只是中間有一個空的span標簽。

//Example code 1
<input type="text" name="str_cvv" value="" maxlength="3" size="4" id="CVV">
<span class="reqd">*</span>

//Example code 2
<span class="regfieldlabel">
      <input type="text" name="nameOnCard" size="30" maxlength="50" id="cardName" value="">
</span>
<span class="reqd">*</span>

//Example code 3
<span class="regfieldlabel">
      <input type="text" name="nameOnCard" size="30" maxlength="50" id="cardName" value="">
</span>
<span class="regfieldlabel"> </span>
<span class="reqd">*</span>

<script>
$(function() {
    $("span").each(function(){
        //Highlight all fields that have a red asterisk at the end for validation
        if ($(this).hasClass('reqd')) {
            $(this).prev().attr('data-rule-required', true).attr('data-msg-required', 'This field is required');
            $(this).prevUntil('.regfieldlabel').find('input').attr('data-rule-required', true).attr('data-msg-required', 'This field is required');

        }
    });
});
</script>

您不想使用prevUntil ,從文檔中您將看到:

描述:獲取每個元素的所有在前同級,直到但不包括與選擇器 ,DOM節點或jQuery對象匹配的元素

結果, $(this).prevUntil('.regfieldlabel')實際上為空。

對於示例2,您仍然只想使用prev

$(this).prev('.regfieldlabel').find('input')

對於一般的解決方案,您將必須檢查自己所處的情況,以執行正確的操作:

$("span.reqd").each(function(){

    var $this = $(this);
    var $prev = $this.prev();
    var $input = $([]); // init to empty

    if($prev.is("input")){
        // EXAMPLE 1
        $input = $prev;

    } else if($prev.is(".regfieldlabel")){
        var $innerInput = $prev.find("input");

        if($innerInput.length > 0){
            // EXAMPLE 2
            $input = $innerInput;
        } else {
            $prev = $prev.prev(".regfieldlabel");
            $innerInput = $prev.find("input");

            if($innerInput.length > 0){
                // EXAMPLE 3
                $input = $innerInput;
            } else {
                // unknown case, maybe do something here
            }
        }
    } else {
        // unknown case, maybe do something here
    }

    $input.attr('data-rule-required', true).attr('data-msg-required', 'This field is required');

});

http://jsfiddle.net/DVSeg/2/

暫無
暫無

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

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