我有一个带有两个选择下拉列表的html表单。每个人都有你离开/去的相同网站。我试图获取每个ID并将它们存储为单独的变量,但每次选择新选项时,变量都会重置为undefined
。我的代码如下所示:
$('select[name=Depart], select[name=Return]').change(function(){
var id = $(this).attr('id');
var depart_id;
var return_id;
// Grabs the place you left from
var dep = $('select[name=Depart] option:selected').val();
// Grabs the place you traveled to
var ret = $('select[name=Return] option:selected').val();
// Grabs the day in the log as a string
var day_id_raw = $(this).closest('tr').attr('id');
// Creates a jQuery object from the string above
var day_id = $('#' + day_id_raw);
// Creates a substring of the string above cutting it off at the day number in the log. E.g. "Day 1" in the log becomes the number "1".
var day_num = day_id_raw.substring(3, day_id_raw.length);
//Creates a jQuery object for the miles of the day table column
var miles_today = $('#miles_day' + day_num);
if($(this).is($('select[name=Depart]'))){
depart_id = id;
}
if($(this).is($('select[name=Return]'))){
return_id = id;
}
// Checks if the place you left from contains a column to output how many miles you traveled that day.
if(day_id.has(miles_today)){
miles_today.text(depart_id + "\n" + return_id);
}
)};
最后一个if
语句仅用于调试目的。 miles_today
是一个空白div,我正在编写内容以测试变量是否实际正常工作。就像我之前说的那样,每次在选择输入时更改选项时,都会清除备用变量。提前谢谢。
id
,但在其他字段“{返回到id
时未定义”。我希望在更改选择选项时显示两个id
。
答案 0 :(得分:2)
将它们置于更改功能之外,并在任何您喜欢的地方使用它们:
var depart_id = $('select[name=Depart]').prop('id'),
return_id = $('select[name=Return]').prop('id');
$('select[name=Depart], select[name=Return]').on('change', function(){
miles_today.text(depart_id + "\n" + return_id);
});
但你确定你不应该得到这个价值吗?