如果我有一个表格,可能有 1 个或多个部分用于用 laravel 表格装箱的地址:如下所示:
{{ Form::text('street1', '', ['class' => '']) }}
{{ Form::label('state1', 'State', ['class' => '']) }}
{{ Form::label('country1', 'Country', ['class' => '']) }}
{{ Form::text('street2', '', ['class' => '']) }}
{{ Form::select('state2', 'State', ['class' => '']) }}
{{ Form::select('country2', 'Country', ['class' => '']) }}
以及根据所选国家/地区填充州选择器的脚本。因此,如果country1
设置为美国,则state1
的下拉列表将仅是美国的州。我可以通过使用每个字段的 ID 对我的 JQuery 脚本进行硬编码来做到这一点。但是,我想动态执行此操作,因为可能不止 2 个字段。
$('select[id="country1"]').on('change', function() { ... }
有没有办法创建一个循环,为每组字段生成on.change
事件?
只需将每个组包装在自己的容器中即可。然后,您可以为每个选择使用一个公共类。
要获取关联的状态,请选择查找包装容器并查找()其中状态选择的类
$('.country').change(function() {
const $stateSelect = $(this).closest('.group').find('.state');
getStates(this.value).then(states => {
$stateSelect.html(() => states.map(el => new Option(el.txt, el.k)));
});
});
// mock server request asynchronous method
function getStates(key) {
const states={us:[{k:"al",txt:"Alabama"},{k:"hi",txt:"Hawaii"}],cdn:[{k:"ont",txt:"Ontario"},{k:"alb",txt:"Alberta"}]};
return Promise.resolve(states[key]);
}
.group { margin:0 2em 1em 2em; border: 1px solid #ccc; padding:1em}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="group">
Country: <select class="country" name="country1">
<option value=""> -Select Country</option>
<option value="cdn">Canada</option>
<option value="us">USA</option>
</select>
States: <select class="state" name="state1"></select>
</div>
<div class="group">
Country: <select class="country" name="country2">
<option value=""> -Select Country</option>
<option value="cdn">Canada</option>
<option value="us">USA</option>
</select>
States: <select class="state" name="state2"></select>
</div>
无需为每组字段生成on.change
事件。您可以在所有selects
上应用 onChange 事件,并且在函数主体中,您可以使用this
获取当前正在更改的select
,并且可以执行类似
$('select').on('change', function(){
/*
for example you have different ids for different selects then you can
simply get the id of the current element to recognize it.
*/
id = $(this).attr('id');
// then place the condition to recognize and do your stuff.
if (id == 'country1'){
// code stuff for country 1
}elseif(id == 'country2')
{
// code stuff for country 2
}
value = this.value;// example get the value
});
编辑
无论您有多少select
,都必须根据id
或任何data-attribute
附加唯一标识符。
因此,如果您不想使用太多if and else
,也可以尝试这样做,尝试将数字 ID 提供给国家/地区(如id=1
)和相关字符串级联 id 到其状态(如id=state1
)。
假设您所在的国家/地区select
有id='1'
,您所在的州select
有其他国家/地区的select
id='state1'
等等,那么您可以使用以下代码段。请注意,您可以简单地在循环中使用字符串串联动态生成ids
,以便创建 html 元素。
$('select').on('change', function(){
/*
for example you have different ids for different selects then you can
simply get the id of the current element to recognize it.
*/
id = $(this).attr('id');// say if id=1 for country
// then get the respective state selector with
state = 'state'+id; // respective state selector identifier, state1
stateSelector = "#"+state;
$(stateSelector ).val();// example get the value of respective state or whatever.
});