jquery addClass函数无法正常工作而不会抛出任何错误

时间:2018-05-30 14:56:25

标签: javascript jquery html html5 css3

我想动态地(在点击时)将“selected”类添加到div元素,但它既没有工作也没有抛出错误。即使在控制台中,它也只是在没有工作或抛出错误的情况下运行。

<div class="col s8 m4 card-box cursor-pointer">
<div class="card"
     id="object__{{ key }}"
     name = "{{ value }}__{{ key }}__{{ qb_id }}"
     oncontextmenu="chapter_context_menu(event, {{ qb_id }}, {{ key }}, '{{ value }}');">
    <div class="card-content  light-blue lighten-4">
        <span class="card-title black-text">{{ value }}</span>
        <p class="grey-text text-darken-2">Chapter {{ forloop.counter }}</p>
    </div>
    <div class="card-action">
        {% include 'question_edition/reusable/edit_chapter/edit_chapter_icon_trigger.html' %}
        {% include 'question_deletion/reusable/delete_chapter/chapter_delete_icon_trigger.html' %}
    </div>
</div>

function object_selected(card_id) {
   object_unselected();
   console.log("#"+card_id);
   var card = $('#'+card_id);
   card.addClass("object-selected");
}

$(".card").click(function(e){
    object_selected($(this).attr('id'));
});

控制台和警报工作正常,没有错误。但班级名单保持不变。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
   $('.card').on('click', function(){     /* $(_selector_).no('click',...) for work if dynamically adding divs*/
   	      /* for remove all selected class */
   	    $('.card').removeClass('selected');
   	    /* for add selected class on this div  */
   	    $(this).addClass('selected');
   });
&#13;
/* all css only for demonstration */       
       .card{
       	  border-style:solid;
       	  border-color:gray;
       	  border-width:4px;
       	  padding:2px;
       	  margin:1px;
       	  cursor:pointer;
       }
       /* add declare selected class after main class */
       .selected{
       	  border-color:red;
       }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <div class="card">card1</div>
    <div class="card">card2</div>
    <div class="card">card3</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

切换课程&#39;已选择&#39;点击,如果再次点击则删除它,等等每次点击/取消点击时,如开关

jQuery('.card').off().on('click', function card_click(){
   jQuery(this).toggleClass('selected');
});

只需添加“已选择”等级&#39;点击

jQuery('.card').off().on('click', function card_click(){
   jQuery(this).addClass('selected');
});

在你的例子中

  

var card = $(&#39;#&#39; + card_id);

错误的部分是 $(&#39;#&#39; + card_id); 不是DOM对象。如果您的DOM对象具有特定的card_id

,您应该这样写
  

var card = jQuery(&#34; \&#34;#&#34; + card_id +&#34; \&#34;&#34;);