Javascript 如何使用$(this)使不同ID和名称的两种选定形式返回其ID?
我有一个带有两个选择下拉列表的html表单。每个网站都有您离开/前往的相同网站。我试图获取每个变量的ID,并将其作为单独的变量存储,但每次选择新选项时,变量都会重置为未定义。我的代码如下所示:Javascript 如何使用$(this)使不同ID和名称的两种选定形式返回其ID?,javascript,jquery,html,Javascript,Jquery,Html,我有一个带有两个选择下拉列表的html表单。每个网站都有您离开/前往的相同网站。我试图获取每个变量的ID,并将其作为单独的变量存储,但每次选择新选项时,变量都会重置为未定义。我的代码如下所示: $('select[name=Depart], select[name=Return]').change(function(){ var id = $(this).attr('id'); var depart_id; var return_id; // Grabs the
$('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,我正在向其写入内容,以测试变量是否实际工作。正如我前面所说的,每次我更改任一选择输入上的选项时,备用变量都会被清除。提前谢谢
编辑:很抱歉回复太晚,措辞含糊不清。以下是我的工作示例:
只需在“天数”字段中输入1或2,它就会添加一个新行。如果您单击“已离开”的选择菜单并选择一个选项,它将在左侧的字段中输出其
id
,但对于返回到的id
的另一个字段,该字段未定义。我想在更改选择选项时显示两个id
s 将它们置于更改功能之外,并在您希望的任何地方使用它们:
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);
});
但是您确定不应该获取该值吗?您想在更改处理程序之外声明
depart\u id
和return\u id
?或者你所说的“重置为未定义”是什么意思?@Bergi-你真的需要更新ID吗,它不太可能改变吗?呃,不,我不知怎的想到OP希望这些变量根据当前的选择而改变。或者可能他有多个选择,名字相同,但ID不同……但是的,可能没有多大意义。GN8:-)