jQuery .change() 未按预期响应


jQuery .change() not responding as expected

我有一个select,我正在尝试对它进行jQuery .change事件。由于某种原因,它无法识别选择的id。它是通过对创建选择及其选项的 php 文件的另一个AJAX调用来构建的。

<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>';

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

这意味着它是动态添加到 DOM 中的,因此需要事件委派。 jQuery 1.7+ 使用 .on() 方法以便正确绑定。

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

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

此外,真的没有理由像您一样尝试获得价值。你在元素内部,因此可以通过this哪个是本机javascript对象或$(this)哪个是jQuery对象来访问它,无论哪种方式都可以正常工作。

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