单击检查元素不工作jquery

时间:2015-02-07 15:41:34

标签: jquery css click

我有一个对话框,可以从ajax调用中获取学生列表,我使用.html() jquery方法加载数据。

我把这样的html数据放到对话框中。我想让每个学生的名字都可以点击。当我点击第一个时,所选.student_list_div的背景应该是green。如果我再次点击,我应该将其设为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;
        });

请帮帮我

4 个答案:

答案 0 :(得分:1)

除了任何其他问题,内联元素(如锚)不能包含元素(如div)。

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

答案 1 :(得分: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;
 });

重要提示:锚 a 不能包含div,请改用<{1}}

答案 2 :(得分:1)

您不需要在第一个单击事件处理程序中绑定其他单击事件处理程序。此外,如果确实如此,我认为您不会将clicked属性更改为false。

&#13;
&#13;
 $("#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;
 });
&#13;
&#13;
&#13;

你也可以通过“.clicked”来实现同样的效果。在点击时使用jQuery&#39; toggleClass进行切换。

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

答案 3 :(得分:0)

您需要的只是动态创建元素的事件绑定。见:

Event binding on dynamically created elements?