我的HTML代码:
<td>
<select name="fieldType" class="form-control show-dropdown-modals">
<option>Text Input</option>
<option value="codes-dropdown" data-toggle="modal" data-target="#codesDropdownModal" for="codesDD" for-display="codesDDDisplay">Codes Dropdown</option>
<option>Date</option>
</select>
</td>
<td>
<input type="text" name="codesDDDisplay" id="codesDDDisplay" value="" class="form-control hidden" readonly="readonly"/>
<input type="hidden" name="codesDD" id="codesDD" value="" />
</td>
此选择会使用此代码打开模态
<div class="modal fade" id="codesDropdownModal" tabindex="-1" role="dialog" aria-labelledby="codesDropdownModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Select Codes</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<label>Name</label>
<select class="form-control codes-table">
<option value="AGENCY">Agency</option>
<option value="OFFICE">Office</option>
</select>
</div>
<div class="col-md-6">
<label>Option</label>
<select class="form-control codes-column">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a type="button" class="btn btn-primary add-codes" href="#">Ok</a>
</div>
</div>
</div>
</div>
jQuery代码(ES6)
registerPageEvents() {
$('#codesDropdownModal').on('show.bs.modal', (event) => {
const targetInput = $(event.relatedTarget).attr('for'); //this gets undefined
const targetDisplay = $(event.relatedTarget).attr('for-display'); //this gets undefined
this.registerCodesModalEvents(targetInput, targetDisplay);
});
}
registerCodesModalEvents(targetInput, targetDisplay) {
$('.add-codes').unbind();
$('.add-codes').click(() => {
this.saveCodesSelection(targetInput, targetDisplay);
$('#codesDropdownModal').modal('hide');
});
}
saveCodesSelection(targetInput, targetDisplay) {
let displayTable = $('#codesDropdownModal').find('.codes-table').val();
let displayColumn = $('#codesDropdownModal').find('.codes-column').val();
let displayText = displayTable + '.' + displayColumn;
let value = displayText;
$('input[name="' + targetInput + '"]').val(value);
$('input[name="' + targetDisplay + '"]').val(displayText);
}
此时,我得到的错误是targetInput和tagetDisplay都未定义(请忽略两者都具有相同的值)。除此之外,一切顺利。