簡體   English   中英

Jquery Foreach在Foreach內部

[英]Jquery Foreach inside Foreach

我正在嘗試在另一個foreach中進行一次foreach。 第一個是foreach每個找到的WodTabIndex類,第二個是每個找到的輸入,鏈接和選擇。

這是我的代碼

var StartId= 500; $('.WodTabIndex').each(function(){
        var $this = $(this);
        $this.children(':input:visible, input[type="checkbox"], a, select').each(function(i){
            (this).attr('tabindex', StartId + i);
                   (this).attr('tabindex', StartId + i);
        });
    });

我做錯了事,但我不知道怎么辦。 因為永遠不要進入秒foreach。

小提琴示例: https : //jsfiddle.net/lfvo/wk3w237y/

 for (var i = 0; i <= $('.WodTabIndex').length; i++) { var $this = $($('.WodTabIndex')[i]).children(':input:visible, input[type="checkbox"], a, select'); for (var ii = $($this).length - 1; ii >= 0; ii--) { $($($this)[ii]).attr("tabindex", ii+500); console.log("Row: "+i+" Checkbox index "+ii+" have attr tabindex: "+(ii+500)); // inspect element to see result // each checkbox have tabindex 500, 501, 502, ... } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="WodTabIndex"> <input type="checkbox"> </div> <div class="WodTabIndex"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> </div> <div class="WodTabIndex"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> </div> 

發布的代碼有兩個問題:

首先,你需要使用.find而不是.children 孩子們只會看着直接的后代 ,而不是物品下方的整個DOM。

因此,對於此html:

<div id='top'>
    <ul>
      <li></li>
      <li></li>

帶有$("#top").children("li")將找不到li

第二個是你需要在循環內使用$(this)否則你會得到this.attr is not a function


從問題中更新了代碼:

var startId = 500; 
$('.WodTabIndex').each(function(){
    var $this = $(this);
    $this.find('input:visible, input[type="checkbox"], a, select').each(function(i){
        $(this).attr('tabindex', startId + i);
    });
});

暫無
暫無

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

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