2013-03-28 36 views
0

我正在研究一個小腳本,並且發現了一些有重複元素的東西。在這種情況下,$('#theSelect1 ..')被重複,我想避免它。避免在jQuery回調中重複選擇器

$('#theSelect1').change(function(){ 
     //console.log ($(this)); 
     console.log( 
     $("#theSelect1 option:selected").text() // is there a way to change #theSelect1 to be $(this) inside this statement? I try not to repeat things. 
     ); 
}) 

這是HTML

  <select id="theSelect1"> 
      <option value="foo" selected="selected">1</option> 
      <option value="bar">2</option> 
      <option value="foobar">3</option> 

謝謝

+1

簡短的回答 - 是的。替換$(「#theSelect1選項:選中」).text()with $(this).find('option:selected「)。text() – Derek

+0

哇嘎快回復!謝謝! – Matt

回答

4

你可以做到以下幾點:

$(this).children("option:selected").text(); 

這會去翻的子元素目前的元素與您的選擇器匹配的nts。這看起來只是在第一級的後代,因此使用下面的,如果你想要的任何後代:

$(this).find("option:selected").text(); 
2

你可以這樣做:

var selectOne = $('#theSelect1').change(function(){ 
        selectOne.find('option:selected').text(); 
       }); 
+0

爲什麼要這樣做使用$ (this)出於興趣? – CodePB

+0

您將對象緩存在'selectOne'變量中。這樣,如果您再次需要它,則不必查詢DOM。 – Jack

+0

$(this)不會再次查詢DOM – CodePB