在使用相同类名(jQuery)的多个元素中定位单个输入时遇到问题

时间:2017-08-01 23:11:24

标签: javascript jquery html drop-down-menu targeting

我有一个包含li元素列表的页面,每个元素都称为.section。该页面仅以一个部分开头,但用户可以通过单击添加更多内容。每个部分都有一个名为.wip-location的下拉列表和三个名为.section-number.section-name.section-description的输入字段。 (-number和-description输入是无关紧要的,但我将它们包含在这里,以防它们引起问题。)

每次更改下拉列表时,我都希望所选文字填入.section-name输入。

这是第一次(当页面上只有一个.section.wip-location.section-name时),但只要用户添加更多.section s,似乎Jquery无法确定要对哪个元素进行操作,并且没有填充任何输入。

HTML

<li class="section">
    <div class="form-group row">
        <label class="col-sm-2 text-sm-right">Section Number</label>
        <div class="col-sm-7">
            <input class="section-number" type="number" step="0.01" min="1" />
        </div>

        <label class="col-sm-2 text-sm-right">Section Name</label>
        <div class="col-sm-7">
            <input class="section-name" />
        </div>
    </div>

    <div class="form-group row">
        <label class="col-sm-2 text-sm-right">Section Description</label>
        <div class="col-sm-7">
            <textarea class="section-description" />
        </div>

        <label class="col-sm-2 text-sm-right">WIP Location</label>
        <div class="col-sm-7">
            @Html.DropDownListFor(m => m.WipLocation,
                                        new SelectList(Model.WipLocations, "Key", "Value"),
                                        "-- select --",
                                        new { @class = "wip-location" })
        </div>
    </div>
</li>

的jQuery

// Automatically add Wip Location choice to Section Name input
$('.wip-location').change(function () {
    var $location = $('option:selected', $(this)).text();
    var $section = $(this).closest('.section');
    var $sectionName = $section.find('.section-name');

    $sectionName.val($location);
});

正如我所说,当页面上只有一个.section.wip-location时,它的效果非常好。我怀疑当有多个.wip-location或者其他东西时,jQuery会感到困惑,但我不确定这是不是真正的问题或者如何修复它。

1 个答案:

答案 0 :(得分:1)

由于它是动态添加的,您可以尝试调用此事件:

$(document).on('change', '.wip-location', function(){/*...*/})