2013-10-26 31 views
0

我有一個select,我試圖做一個jQuery .change事件。由於某些原因,它不能識別選擇的id。它通過調用另一個AJAX調用來創建選擇及其選項的php文件。jQuery .change()沒有按預期做出響應

<script> 
    $(document).ready(function() 
    { 
     $("#unitselector").on('change', function() 
     { 
      console.log('made it'); 
      var unit=$('#unitselector').filter(':selected').val(); 
      var dataString = {unit:unit}; 
      console.log(dataString); 
      $.ajax({ 
       type: "POST", 
       url: "classes/unit_info.php", 
       data: dataString, 
       cache: false, 
       success: function(html) 
       { 
        $('.unitinfo').html(html); 
       } 
      }); 
     }); 
    }); 
    </script> 

相關PHP:

echo '<select id="unitselector" name="units">'; 
while($row = mysqli_fetch_assoc($result)) 
{ 
    $units[] = $row['unit_name']; 
    echo '<option value="'.$row['unit_name'].'">'.$row['unit_name'].'</option>'; 
} 
echo '</select>'; 

回答

1

It is built through another AJAX call to a php file that creates the select and its options.

這意味着它的動態添加到DOM,因此需要事件委託。 jQuery 1.7+ uses the .on()方法才能正確綁定。

$("#unitselector").on('change', function() 

$(document).on('change', '#unitselector', function() 

而且,真的沒有理由去嘗試,並得到像你這樣做的價值。您位於元素內部,因此可以通過this這是本地javascript對象或$(this)這是一個jQuery對象來訪問它,無論哪種方式都可以正常工作。

var unit = $(this).val(); 
//or 
var unit = this.value; 
+0

太棒了,謝謝。 –