我有许多名称为emp的下拉框,所以在下面的代码中,我尝试打印框的ID,但有些却是空的,我在这里做错了什么

  var selected_emp = $('select[name="emp"]');
     selected_emp.children('option:selected').each(function() {
        if($(this).val() != '' && $(this).val() != null)
        {
           alert($(this).attr('id'));
        }
     });

最佳答案

您的选项元素是否具有id属性?通常,option元素只有一个值和包含的文本。您可以执行以下操作来打印框的ID和框中的选定值:

 var selected_emp = $('select[name="emp"]');
 selected_emp.children('option:selected').each(function() {
    if($(this).val() != '' && $(this).val() != null)
    {
       alert($(this).parent().attr('id') + ":" + $(this).val());
    }
 });


或者,仅遍历选择框本身:

$('select[name="emp"]').each(function() {
    alert(this.Id);
}

关于javascript - 在下拉框中获取所选项目的ID属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6210871/

10-12 00:46
查看更多