2015-02-07 49 views
0

我有一个对话框,从ajax调用中获得学生列表,我用jQuery的.html()方法加载数据。检查一个元素被点击不工作jquery

我把这样的html数据放到对话框中。我想让每个学生的名字都是可点击的。当我点击第一个时,所选.student_list_div的背景应该是​​。如果我再次点击,我应该使它background none。如果再次点击,颜色应该是绿色的,以使用户知道它被选中或不。我也做了jquery方法,但它不能正常工作。

<a href='' class='student_list' id='studentid1'><div class="student_list_div"> 
StudentName1</div></a> 
<a href='' class='student_list' id='studentid2'><div class="student_list_div"> 
StudentName2</div></a> 
and so on....... 

我的jquery方法是这样的。

$("#dialog_wrapper").on('click','.student_list',function(){ 
      if($(this).data('clicked')) 
      { 
       $(this).find('.student_list_div').css('background-color','none'); 
      } 
      else 
      { 
       $(this).click(function(){ 
        $(this).data('clicked',true); 
        $(this).find('.student_list_div').css('background-color','green'); 
       }); 
      } 


      return false; 
     }); 

请帮我

+0

你可以发布jsfiddle吗? – 2015-02-07 15:43:03

+0

你为什么要绑定另一个点击事件处理程序。删除'$(this).click(function(){' – Satpal 2015-02-07 15:45:27

回答

1

你并不需要你的第一个点击事件中绑定额外的点击事件处理处理程序。此外,我认为如果它是真实的,你不会将clicked属性更改为false。

$("#dialog_wrapper").on('click', '.student_list', function() { 
 
    if ($(this).data('clicked')) { 
 
    $(this).find('.student_list_div').css('background-color', 'none'); 
 
    $(this).data('clicked', false); 
 
    } else { 
 
    $(this).data('clicked', true); 
 
    $(this).find('.student_list_div').css('background-color', 'green'); 
 
    } 
 

 

 
    return false; 
 
});

而且你可以通过具有“.clicked”类和使用jQuery的toggleClass到点击时切换它达到同样的效果。

$("#dialog_wrapper").on('click', '.student_list', function() { 
 
    $(this).find('.student_list_div').toggleClass('.clicked') 
 
});
.clicked { 
 
    background-color: green; 
 
}

+0

你的运行代码片段没有显示任何东西 – Techy 2015-02-07 15:54:53

+0

第二个版本(切换一个类)绝对是一个更好的选择。请注意,原始HTML也是无效的(div是一个* block *元素,因此在一个* inline *元素的锚点内无效) – 2015-02-07 15:59:56

1

除此之外的任何其他问题,直列元素,就像一个锚,不能包含元素(如一个div)。

改为使用<span> s作为内部元素。

+0

我已经使用了跨度,但是一旦它被选中,背景颜色也不会再去。 – Techy 2015-02-07 15:53:00

+0

您也在点击处理程序中连接点击处理程序 - 从来不是一个好主意。 – 2015-02-07 15:56:52

+0

我明白了我的错误。谢谢让我意识到。我也提出了你的答案 – Techy 2015-02-07 15:57:48

1

您正在绑定单击处理程序中的单击事件处理程序。删除$(this).click(function(){

使用

$("#dialog_wrapper").on('click', '.student_list', function() { 
    if ($(this).data('clicked')) { 
     $(this).find('.student_list_div').css('background-color', ''); 
    } else { 
     $(this).data('clicked', true); 
     $(this).find('.student_list_div').css('background-color', 'green'); 
    } 
    return false; 
}); 

重要:锚一个不能包含div,使用span代替

+0

这是第一次工作。即如果它不是锚点标签没有点击,它会使第一次点击时背景绿色。如果我点击再次,背景颜色不会删除 – Techy 2015-02-07 15:50:33

+0

@Techy,尝试与'.css('background-color','')' – Satpal 2015-02-07 15:54:16

+0

这也不工作。当我添加$(this)。数据('点击',错误);在第一个条件内工作,感谢您的帮助。 – Techy 2015-02-07 15:56:52