在jquery中使用变量作为占位符更新选择选项
在我的项目中,一个页面可以有一个或多个选项,选项中填充了数据库值,这意味着具有不同id的选择字段可以有相同的选项 例如:在jquery中使用变量作为占位符更新选择选项,jquery,html-select,Jquery,Html Select,在我的项目中,一个页面可以有一个或多个选项,选项中填充了数据库值,这意味着具有不同id的选择字段可以有相同的选项 例如: <select id="set-0-costID"> <option value="1">Name1</options> <option value="2">Name2</options> <option value="3">Name3</options> </s
<select id="set-0-costID">
<option value="1">Name1</options>
<option value="2">Name2</options>
<option value="3">Name3</options>
</select>
<select id="set-1-costID">
<option value="1">Name1</options>
<option value="2">Name2</options>
<option value="3">Name3</options>
</select>
但我必须更加灵活,并希望将所有可能的字段名存储在dict中,然后循环通过它
这个代码不起作用。无错误,但选项未更新
var fields=['cost1ID', 'cost2ID']; var field_name="";
for (f in fields) {
field_name = fields[f];
$("[id$=field_name]").each(function(index, elem){
var $el = $('#' + elem.id);
$('#' + elem.id + ' option[value="1"]').text('Name1new');
$el.selectpicker("refresh");
});
};
我猜Jquery将field_name解释为要搜索的名称,而不是变量。
我必须如何更改代码才能使其正常工作?
谢谢我不确定这是否能解决问题,但请尝试更换:
$("[id$=field_name]").each(function(index, elem){
作者:
希望这有帮助。有点晚了,但是您考虑过数据属性吗?这可能会使您的代码更加灵活 在这里,我创建了一个名为
数据更新
的属性,它列出了要更新的每个ID(用空格分隔):
名称1
姓名2
名称1
姓名2
名称1
姓名2
jQuery:
$(document).on('change', '[data-update]', function(){
var a = $(this).data('update').split(' '), index;
for (index = 0; index < a.length; ++index) {
$(a[index]).val( $(this).val() );
}
});
$(文档).on('change','data update',function(){
变量a=$(this).data('update').split(''),index;
对于(索引=0;索引
这也适用于以下类:
$("[id$='"+field_name+"']").each(function(index, elem){
<select id="set-0-costID" data-update="#set-1-costID #set-2-costID">
<option></option>
<option value="1">Name1</option>
<option value="2">Name2</option>
</select>
<select id="set-1-costID" data-update="#set-0-costID #set-2-costID">
<option></option>
<option value="1">Name1</option>
<option value="2">Name2</option>
</select>
<select id="set-2-costID" data-update="#set-0-costID #set-1-costID">
<option></option>
<option value="1">Name1</option>
<option value="2">Name2</option>
</select>
$(document).on('change', '[data-update]', function(){
var a = $(this).data('update').split(' '), index;
for (index = 0; index < a.length; ++index) {
$(a[index]).val( $(this).val() );
}
});