li
要素のリストを持つページがあり、それぞれが.section
と呼ばれています。ページは1つのセクションから始まりますが、ユーザーはクリックしてさらに情報を追加できます。各セクションには、.wip-location
というドロップダウンと、.section-number
,.section-name
、.section-description
という3つの入力フィールドがあります。 (番号と説明の入力は関係ありませんが、問題が発生した場合に備えてここに含めました)同じクラス名(jQuery)を持つ複数の要素の1つの入力を対象とすることに問題がある
ドロップダウンが変更されるたびに、選択したテキストを.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の一つだけ.section
、ページ上の.wip-location
あり
// 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);
});
私が言ったように、それは完璧に動作します。私は、複数の.wip-location
があるときにjQueryが混乱すると思うが、それが本当に問題か、それを修正する方法がわからない。動的にあなたがこのようなイベントを呼び出すために試みることができる追加されているので
使用イベント委任 – guest271314