2017-07-29 87 views
2

我的確注意了一些其他的答案,所以在這方面,和from one of them我發現我在這裏使用的一個,但它看起來像它永遠不會發生,因爲這不是return false;發射console.log(myId);通常應該。如何查找.each()的結尾?

 let pattern = new RegExp('^\/wiki\/'); 
     var total = doSelect("Location").siblings('td').find('a').length; 
     doSelect("Location").siblings('td').find('a').each(function(i, el, index) { 
     var result = $(this).attr('href').replace(pattern, ''); 
     console.log(result); 
     if (index === total - 1) { 
      myId = item.pageid; 
      console.log(myId); 
      return false; 
     } 
     }); 

我甚至嘗試與沒有積極成果this other SO answer建議如下:

let pattern = new RegExp('^\/wiki\/'); 
    doSelect("Location").siblings('td').find('a').each(function(i, el) { 
    var result = $(this).attr('href').replace(pattern, ''); 
    console.log(result); 
    }).promise().done(function(){ 
    myId = item.pageid; 
    console.log(myId); 
    return false; 
    }); 

UPDATE

關於:item (用下面的數據沒有問題),上述代碼在以下範圍內data each

$.getJSON(url,function(data){ 
    $.each(data, function(i, item) { 
+0

是什麼'item'? –

+1

@ er-han更新了您的問題的答案,以防其他人需要 –

+1

您不應該在if語句中簡單地使用'i'而不是'index'嗎? –

回答

2

你的第一個選項有一個sintax錯誤:

.each(function(i, el, index) must be .each(function(index, el)

let pattern = new RegExp('^\/wiki\/'); 
    var total = doSelect("Location").siblings('td').find('a').length; 
    doSelect("Location").siblings('td').find('a').each(function(index, el) { 
    var result = $(this).attr('href').replace(pattern, ''); 
    console.log(result); 
    if (index === total - 1) { 
     myId = item.pageid; 
     console.log(myId); 
     return false; 
    } 
    }); 
2

each()回調沒有第三個參數。你所說的index是未定義的。第一個參數i是指數

更改爲:

if (i === total - 1) 
+0

哦,我明白了!現在測試 –

1

的問題是,該變量index沒有定義,所以if (index === total - 1)永遠不會返回true。

呼叫的功能.each

.each(function(i, el, index) 

應該

.each(function(i, el) 

然後測試應該是

if (i === total - 1) 

CF jQuery API documentation,說明該函數取兩個參數:

.each(function)

function Type: Function(Integer index, Element element)

0

您還可以使用.last()功能:

1.

//insert own jq function 
$.fn.myTask = function(){ 
    myId = item.pageid; 
    console.log(myId); 
    //My suggestion: return this; 
    return false; 
} 

2.

//than replace your lines 
    let pattern = new RegExp('^\/wiki\/'); 
    var total = doSelect("Location").siblings('td').find('a').length; 
    doSelect("Location").siblings('td').find('a').each(function(i, el) { 
    var result = $(this).attr('href').replace(pattern, ''); 
    console.log(result); 
    }).last().myTask(); 
+0

謝謝,現在就試試看,因爲它會使它更小 –