2012-07-01 50 views
2

考慮下面的代碼:如何引用jQuery匹配元素的值?

$(".force-selection").blur(function() { 
     var value = $('matched-item').val(); 
     //check if the input's value matches the selected item 
     if(value != $('#matched-item').data('selected-item')) { 
      //they don't, the user must have typed something else 
      $('#matched-item') 
       .val('') //clear the input's text 
       .data('selected-item', ''); //clear the selected item 
     } 
}); 

如何指的是由$(「力的選擇。」)jQuery選擇相匹配的元素?我不是匿名JS功能非常清楚,我很困惑,人怎麼知道有時聲明它們是這樣的:

function() 

,有時是這樣的:

function(event) 

,有時像這樣:

function(element, update, options) 

和所有其他方式。

+1

將'this'存儲在變量中。 PS。你在'var value = ..'行的選擇器中缺少一個尖銳的('#')。 –

+1

這些功能之間的差異只是他們採取的參數。 – Esailija

+0

爲什麼不緩存選擇器?完成 – elclanrs

回答

1

您可以使用.currentTarget與jQuery的事件對象作爲第一個參數傳遞:

$(".force-selection").blur(function(e) { //<-- define e as parameter for this function. it's short for "event" 
     e.currentTarget; //The element a blur was triggered on 
     var value = $('#matched-item').val(); //<-- add "#" 



     //check if the input's value matches the selected item 
     if(value != $('#matched-item').data('selected-item')) { 
      //they don't, the user must have typed something else 
      $('#matched-item') 
       .val('') //clear the input's text 
       .data('selected-item', ''); //clear the selected item 
     } 
}); 
0

使用這個關鍵字,它指的是當前關閉。用jQuery調用把它包裝起來,它變成被引用的元素。

$(".force-selection").blur(function() { 
    var value = $('matched-item').val(); 
    //check if the input's value matches the selected item 
    if(value != $('#matched-item').data('selected-item')) { 
     //they don't, the user must have typed something else 
     $('#matched-item') 
      .val('') //clear the input's text 
      .data('selected-item', ''); //clear the selected item 
    } 
    //----- 
    $(this) == current .force-selection 
    //----- 
}); 
相關問題