jQuery attr('id')返回undefined

时间:2014-01-01 15:27:24

标签: javascript jquery html ajax dom

我有一个项目列表,当用户点击其中一个项目时,它会被分配一个名为“active-child”的类。此时只能选择一个项目,当用户点击另一个项目时,此项目将被清除“活动子项”类,然后将此类分配给新选择的项目。就像任何其他非多重列表一样。

以下是所选元素的HTML:

<div id="5" class="new-child-item new-child-item-active active-child"> Software </div>

当我想将所选项目的“id”提交给php脚本以进一步处理它时,jquery不会检索该元素的id值并说它是undefined。我获取所选项目的id属性的方法如下:

$('.active-child').attr('id');

我也测试了这个,但仍然返回undefined

$('.active-child:first-child').attr('id');

奇怪的是我首先检查用户是否选择了任何内容,如果是,则执行ajax,此时jquery返回1,表示用户选择了一个项目。这是代码块,它检查选择,然后通过ajax发送它:

 if($('.active-child').length > 0)
                  {
                      $('.new-item-cats-list-holder').empty();
                       $('.new-item-cats-list-holder').hide()
                  $('.big-loader').show();
                      console.log("This is the id: " + $('.new-child-item-active:first-child').attr('id'));
                      $.ajax({
                      url : base_path('ajax/set_credentials/step_2'),
                      type: "POST",
                      data : ({'set_sess':true, 'category' : $('.active-child').attr('id')}),
                      success : function(msg){                                                                  
                        if(msg!=0)
                        {                                                       
                            //window.location.href = base_path('panel/add/step/ads/3');                     

                        }
                      },
                  });
                  }// end of length if

2 个答案:

答案 0 :(得分:1)

ID检索之前的empty()和hide()函数会破坏DOM,并且不允许它存在,然后获取其id值。

答案 1 :(得分:0)

我知道您使用数值作为ID,或者至少具有以数字开头的ID。我的怀疑来自于您的控制台日志返回1,并且您在问题中指定您正在记录活动子项的ID。

这是无效的 - 类和ID必须以字母或下划线或短划线开头,然后是任何字母数字,下划线或短划线字符及其组合。

请参阅此处:Which characters are valid in CSS class names/selectors?http://www.w3.org/TR/CSS21/syndata.html#characters

除非您使用的是HTML5,否则您需要正确声明文档类型:<!DOCTYPE html>

另外,您是否检查过您的ID是否唯一?