简体   繁体   English

jQuery change事件不会在指定选择器上触发

[英]jQuery change event doesn't fire on specified selector

I have the following code: 我有以下代码:

$("select.form-control").change(function () {
    alert($(this).val());
});

In my DOM there is a variable number of select tags that I need to work on, but I can't seem to access their values (in this case, their values) using the above function. 在我的DOM中,我需要处理可变数量的select标签,但是我似乎无法使用上述函数访问它们的值(在这种情况下,它们的值)。 Any idea why this is not working? 知道为什么这行不通吗?

Edit: 编辑:

The piece of code that should trigger the event: 触发事件的代码片段:

     <div class="box box-solid ship-grid">
            <div class="box-header with-border">
                <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
                    <h3 class="box-title">Victory II-Class Star Destroyer</h3>
                    <input type="hidden" value="2" name="ship-id-0" id="ship-id-0">
                </div>
                <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
                    <h3 class="box-title points-counter GreenBold"><span class="point-counter" id="point-counter-0">85</span> points 
                    <i class="fa fa-times delete-from-grid" title="Delete this ship" onclick="deleteShipGrid(this)"></i></h3>
                </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body">
                <div class="col-lg-3 col-md-4 col-sm-12 col-xs-12">
                    <img src="images/ships/empire/victory-II.png" class="ship-grid-image amd-center-img">
                </div>
                <div class="col-lg-9 col-md-8 col-sm-12 col-xs-12">

                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/officer.png" class="grid-upgrade-icon"> Select an Officer</span>
                        <select name="officer-0" id="officer-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No officer</option><option class="tooltip-upgrade-12" value="12">[ +3 ] Director Isard •</option><option class="tooltip-upgrade-13" value="13">[ +3 ] Defense Liason </option><option class="tooltip-upgrade-14" value="14">[ +3 ] Weapons Liason </option><option class="tooltip-upgrade-15" value="15">[ +3 ] Veteran Captain </option><option class="tooltip-upgrade-11" value="11">[ +7 ] Wulff Yularen •</option><option class="tooltip-upgrade-10" value="10">[ +10 ] Admiral Chiraneau •</option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/weapons.png" class="grid-upgrade-icon"> Select a Weapons Team</span>
                        <select name="weapons-team-0" id="weapons-team-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No weapons team</option><option class="tooltip-upgrade-17" value="17">[ +5 ] Sensor Team </option><option class="tooltip-upgrade-18" value="18">[ +6 ] Flight Controllers </option><option class="tooltip-upgrade-16" value="16">[ +7 ] Gunnery Team </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/off.png" class="grid-upgrade-icon"> Select an Offensive Retrofit</span>
                        <select name="offensive-retro-0" id="offensive-retro-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No offensive retrofit</option><option class="tooltip-upgrade-46" value="46">[ +5 ] Expanded Hangar Bay </option><option class="tooltip-upgrade-47" value="47">[ +5 ] Point-Defense Reroute </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/turbo.png" class="grid-upgrade-icon"> Select Turbolasers</span>
                        <select name="turbolasers-0" id="turbolasers-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No turbolasers</option><option class="tooltip-upgrade-36" value="36">[ +5 ] XX-9 Turbolasers </option><option class="tooltip-upgrade-38" value="38">[ +6 ] X-17 Turbolasers </option><option class="tooltip-upgrade-35" value="35">[ +8 ] H9 Turbolasers </option><option class="tooltip-upgrade-37" value="37">[ +10 ] Enhanced Armament </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/ion.png" class="grid-upgrade-icon"> Select Ion Cannons</span>
                        <select name="ions-0" id="ions-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No ion cannons</option><option class="tooltip-upgrade-39" value="39">[ +4 ] Leading Shots </option><option class="tooltip-upgrade-40" value="40">[ +5 ] Ion Cannon Batteries </option><option class="tooltip-upgrade-41" value="41">[ +8 ] Overload Pulse </option>
                        </select>
                    </div>
                    <div class="col-lg-6 col-md-12 col-sm-12 col-xs12">
                        <span class="control-label" style="margin-top: 10px"><img src="images/icons/title.png" class="grid-upgrade-icon"> Select a vessel title</span>
                        <select name="tilte-0" id="title-0" class="form-control" style="margin-top: 10px">
                            <option value="0">No title</option><option class="tooltip-upgrade-32" value="32">[ +8 ] Warlord •</option><option class="tooltip-upgrade-33" value="33">[ +5 ] Corrupter •</option><option class="tooltip-upgrade-34" value="34">[ +12 ] Dominator •</option>
                        </select>
                    </div>
                    <div class="checkbox col-md-12" style="margin-top: 20px;">
                      <label>
                        <input type="checkbox" name="flagship-0" id="flagship-0"> Use this ship as flagship
                      </label>
                    </div>
                </div>
            </div>
            <!-- /.box-body -->
    </div>

Imagine I have more than one of these boxes, and I need a unique function to get every select value plus thier name attribute. 想象一下,我有多个框,而且我需要一个独特的函数来获取每个选择值以及其名称属性。

A big part of the Javascript code is the following: Javascript代码的大部分如下:

$(document).ready(function () {
    $("#grid").css("height", $("#selector").css("height"));

    <?php if($faction_char == 'e'){ ?>
    $("#li-fge").addClass("active");
    <? }else{ ?>
    $("#li-fgr").addClass("active");
    <? } ?>

    var ship_counter = 0;
    var squadron_counter = 0;

    // List object to be populated on submit
    var list = new Object();

    var ship_array = new Array();
    var squadron_array = new Array();

    $('.boostrap-slider').slider();

    $('#points-slider').slider().on('slide', function (ev) {
        setTotalPoints();
    });

    $('#total-points').bind("DOMSubtreeModified", function () {
        checkPoints();
    });

    $('#current-points').bind("DOMSubtreeModified", function () {
        checkPoints();
    });

    $(".ship-selector").click(function () {
        var ship_id = $(this).attr("ship-id");
        var vessel = $(this).attr("vessel");

        // Ship object initialization
        var ship_object = new Object();
        ship_object.builder_id = 0;
        ship_object.list_id = 0;
        ship_object.ship_id = 0;
        ship_object.officer_id = 0;
        ship_object.weapons_team_1_id = 0;
        ship_object.support_team_1_id = 0;
        ship_object.offensive_retrofit_1_id = 0;
        ship_object.defensive_retrofit_1_id = 0;
        ship_object.ordnance_1_id = 0;
        ship_object.turbolasers_1_id = 0;
        ship_object.ion_cannons_1_id = 0;
        ship_object.weapons_team_2_id = 0;
        ship_object.support_team_2_id = 0;
        ship_object.offensive_retrofit_2_id = 0;
        ship_object.defensive_retrofit_2_id = 0;
        ship_object.ordnance_2_id = 0;
        ship_object.turbolasers_2_id = 0;
        ship_object.ion_cannons_2_id = 0;

        $.ajax
                ({
                    type: "POST",
                    url: "server/get_ship.php",
                    data: {
                        'id': ship_id,
                        'vessel': vessel,
                        'counter': ship_counter
                    },
                    cache: false,
                    success: function (data) {
                        $("#ship-grid").append(data);
                        ship_object.builder_id = ship_counter;
                        ship_object.ship_id = parseInt($("#ship-id-" + ship_counter.toString()).val());
                        ship_array.push(ship_object);
                        ship_counter++;
                    },
                    error: function () {
                        alert("AJAX error.");
                    }
                });
    });

    $("select.form-control").change(function () {
        alert($(this).val());
    });

    $("#objective_1").change(function () {
        $.ajax
                ({
                    type: "POST",
                    url: "server/get_objective.php",
                    data: {
                        'id': $("#objective_1").val()
                    },
                    cache: false,
                    success: function (data) {
                        var domData = $.parseJSON(data);
                        $("#obj-1-img").attr("src","images/objectives/" + domData["rows"][0]["cell"][7]);
                    },
                    error: function () {
                        alert("AJAX error.");
                    }
                });
    });

You mention ajax loading. 您提到ajax加载。 Use a delegated event handler, attached to a non-changing ancestor element (eg document ): 使用附加到不变的祖先元素(例如document )的委托事件处理程序:

eg add this 例如添加这个

$(function(){
    $(document).on('change',"select.form-control", function () {
        alert($(this).val());
    });
});

JSFiddle: http://jsfiddle.net/3p1rtjb0/1/ JSFiddle: http : //jsfiddle.net/3p1rtjb0/1/

Delegated events work by listening for the event to bubble up to the ancestor. 委派的事件通过监听事件传到祖先来起作用。 It then applies the selector to only the elements in the bubble-chain (so is very efficient). 然后,它将选择器仅应用于气泡链中的元素(因此非常有效)。 It then calls the function on any matching elements that caused the event. 然后,它在导致事件的所有匹配元素上调用该函数。

The upshot is that the elements only need to match at event time (not when the event was registered). 结果是这些元素仅需要在事件发生时进行匹配(而不是在事件注册时进行匹配)。

Note: I last yeat found a bug, related to styling, that means delegated mouse events attached to body do not fire (if the calculated body height is 0). 注意:我上次发现的是与样式相关的错误,这意味着与body关联的委托鼠标事件不会触发(如果计算出的主体高度为0)。 For that reason I recommend you always use document as the default for delegated event handler (if nothing else is closer/convenient). 因此,我建议您始终使用document作为委托事件处理程序的默认document (如果没有其他更方便的方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM