事件回呼裡的 this 指向觸發事件的元素,要從它往下取子元素,有幾種寫法。以下用 select 的 change 事件做示範。
<select id="city">
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="shenzhen">深圳</option>
</select>
$(function(){
$("#city").change(function(){
// 此時 this 就是 select 元素本身
});
});
兩種常見寫法:
$("#city option:selected").val(); // 用選擇器直接定位
$(this).children('option:selected').val(); // 從 this 往下找
兩者結果相同。差別在於可擴充性:如果頁面上有多個 select,而你把同一段邏輯綁在 class 上,用 $("#city ...") 這種寫死的 id 就會出錯,而 $(this).children(...) 永遠指向「目前觸發的那一個」。
取得文字也是同樣道理:
$(this).children('option:selected').text();
children() 只看直接子元素,find() 會往下找所有後代。對 select 這個結構來說,option 就是直接子元素,用 children() 語意更精確、效能也略好。若結構較深或有多層巢狀,才需要 find()。
$(this "a") // 錯,$ 是函式,不能這樣呼叫
$("this a") // 錯,這會去找 <this> 標籤裡的 a,頁面並沒有這個標籤
正確的組合是 $(this).find("a") 或 $("a", this)。後者是把 this 當成選擇器的第二個參數(context),效果等同於 $(this).find("a"),兩種寫法都可以,挑順手的即可。