我有一个奇怪的问题。我正在尝试更改页面加载时的选定选项。这适用于台式机,但不适用于移动设备。
<select id="gui-form-details-type" name="customer[type]">
<option value="private" selected="selected">Option1</option>
<option value="company">Option2</option>
</select>
我尝试过的事情是这样的:
$(function(){
$('body').live('change','#gui-form-details-type', function() {
$("#gui-form-details-type").find('option[value=private]').removeAttr("selected");
$("#gui-form-details-type").find('option[value=company]').attr('selected','selected');
}).change();
// and
$("#gui-form-details-type").on('change', function(){
.....
}).change();
// and
$(document).on('change', '#gui-form-details-type', function(){
....
}).change()
});
我什至将它包装在页面加载时触发的函数中。是否有任何特定原因导致它在iOS或Android上不起作用?
任何帮助,不胜感激!
这是我建议的解决方法。
function alterGuiFormDetailsType() {
const $element = $('#gui-form-details-type');
if ($element.length) {
$element.find('option[value="private"]').removeAttr('selected');
$element.find('option[value="company"]').attr('selected', 'selected');
}
}
$(document.body).on('change', '#gui-form-details-type', alterGuiFormDetailsType);
alterGuiFormDetailsType();
从事件处理程序中提取逻辑,并在页面加载时直接调用它。如果该元素尚不存在,它将尝试执行,但不会执行任何操作。