无法在新的ajax调用上更改css

时间:2016-01-12 12:34:34

标签: jquery html css ajax django

这是我的HTML

<div id="tabs" >
              <ul class="cat-head">
              <li>All</li>
              {% for category in brandcategory %}
              <li id="cat{{category.id}}" onclick="sendBrandCategory(event, {{category.id}})">{{category}}</li>
              {% endfor %}
              </ul>    
          </div>

这是ajax脚本

<script type="text/javascript">
  function sendBrandCategory(event, category) {
          var data = { category : category , action:'inventory'};
          $.ajax({        
              type: "GET",
              url: "{% url 'storeView'  user=store.user %}",
              data: data,
              success: function(data) {
                  var thumb = $(data).find('#brand');
                  $('#brand').html(thumb);  
                  $('#cat'+ category).css({'background-color':'black'});  
                },
              error: function(response, error) {
                  alert(error);  
              }
          });
      }

</script>

关于ajax的成功,我能够设置第一个li元素css但是在单击第二个li元素时,第一个元素css仍然保留在页面上。我希望一个li元素在ajax成功时具有背景颜色。我可以实现这一点吗。谢谢你

2 个答案:

答案 0 :(得分:1)

您需要在设置新背景之前重置最后的项目:

<script type="text/javascript">
  function sendBrandCategory(event, category) {
          var data = { category : category , action:'inventory'};

          // see here:
          $('[id^="cat"]').each(function() {
               $(this).css('background-color', 'yellow'); // I put yellow but you can put the color you need
          });
          $.ajax({        
              type: "GET",
              url: "{% url 'storeView'  user=store.user %}",
              data: data,
              success: function(data) {
                  var thumb = $(data).find('#brand');
                  $('#brand').html(thumb);  
                  $('#cat'+ category).css({'background-color':'black'});  
                },
              error: function(response, error) {
                  alert(error);  
              }
          });
      }

</script>

答案 1 :(得分:1)

试试这段代码:

 <script type="text/javascript">
   function sendBrandCategory(event, category) {
           var data = { category : category , action:'inventory'};
           $.ajax({        
               type: "GET",
               url: "{% url 'storeView'  user=store.user %}",
               data: data,
               success: function(data) {
                   var thumb = $(data).find('#brand');
                   $('#brand').html(thumb);  
                   $("ul.cat-head li").css({'background-color':'none'});            
                   //this is new line added
                   $('#cat'+ category).css({'background-color':'black'});  
                },
              error: function(response, error) {
                  alert(error);  
              }
          });
      }
</script>