2015-05-28 39 views
1

當我進入頁面時,控制檯出現:未捕獲TypeError:無法使用'in'運算符在undefined中搜索'height', 和之前的值0(從行console.log(我);) 我想在我點擊元素後調用「我」ajax。 我不明白爲什麼apper Uncaught TypeError,爲什麼它沒有任何點擊進入loadSingleIns(i)。

的腳本是:

..... success: function(response) { 
     console.log(JSON.parse(response)); 
       var instructor=JSON.parse(response); 
       var el=""; 
     for(var i=0;i<instructor.length;i++){ 
      $(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns(i)); 
        .... 

而且調用的函數是:

function loadSingleIns(i){ 

     console.log(i); 
$(this).animate({ 
opacity: 0.25, 
left: "+=50", 
height: "toggle" 
}, 5000, function() { 
// Animation complete. 
    }); 
//here i want to call ajax for the element i 

} 

我知道有一些這樣的問題,但我不能找到一個解決方案。

+1

運行沒有因爲括號的點擊功能'()''的功能loadSingleIns'後。這就是函數的調用方式。通過一個參考刪除零件 –

+1

console.log(這個),你會發現它並不指向你認爲它的位置 –

+0

'「.insegnanti#i」+ [i + 1]'讓我有點卷軸。我假設這些元素已經在頁面上?有一個特定的'.insegnanti'類可以讓你點擊(消除循環),並在數據屬性或某個元素中包含元素id。 – Andy

回答

0

你可能需要通過在對第三個參數的處理程序參考你在哪裏調用函數loadSingleIns

$(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns); 

要想從ID,您可以使用下面的代碼我。

function loadSingleIns(){ 
    i = this.id.replace('i',''); 
} 

正如你可以圍繞選擇,".insegnanti#i"+[i+1]作爲IDS的東西都應該是獨一無二的,你可以從選擇刪除類選擇一個附加的註釋。

+1

現在它完美的工作!非常感謝! –

+0

不客氣 – Adil

0

不需要通過PARAMS在loadSingleIns功能,元參和功能時自動通..

$(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns); 

,或者如果你真的想通過PARAMS然後調用回調函數內功能

$(document).on ("click", ".insegnanti#i"+[i+1], function(Event){ 
     loadSingleIns(Event, this); 
}); 
// function with 2 params 
function loadSingleIns(e, refe){ 
    console.log(e, refe) 
} 
0

正如我在評論中提及了這段代碼

for(var i=0;i<instructor.length;i++){ 
    $(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns(i)); 

除了loadSingleIns(i)問題 - 看起來並不正確。這不是真的應該如何使用類。也許你的意思是使用ID屬性,而不是...

假設所有這些元素都在頁面上已經可以完全擺脫循環,使用相同的類捆綁這些元素,並具有元素的ID單獨的屬性:

HTML

<div class="insegnant" data-id="1">Element 1</div> 
<div class="insegnant" data-id="2">Element 2</div> 

JS

$(document).on('click', '.insegnanti', loadSingleIns); 

function loadSingleIns() { 

    var id = $(this).data('id'); 

    $(this).animate({ 
    opacity: 0.25, 
    left: "+=50", 
    height: "toggle" 
    }, 5000, function() { 

    // when the animation has completed run the ajax 
    // this example adds the id on to the end of the URL 
    // you can move this function outside of the animation if you want 
    // I thought it would be better here 
    $.ajax({ 
     url: 'http://demo.com/id=' + id 
     ... 
     success: function (data) { 
     // do something with data 
     } 
    }); 

    }); 
} 
相關問題