Home  >  Q&A  >  body text

javascript - A click event is added to an a tag, and I want to add a class style to the a tag within the time

There are multiple a tags in a span tag, and the a tag is implemented through ajax. I want to add a click event to the a tag, add a class style to the a tag when he clicks, and delete the class styles of other a tags

ajax:

$.ajax({type:"post",url:"carbrand/findCarBrandHot",dataType:"json",success:function(data){
                var html="<a class='on' href='' rel='nofollow'>不限</a> ";
                    var listr = "";                        
                    for(var i = 0; i < data.length; i++){                
                            listr+="<a class=''  title=''  onclick='ch()'>"
                                    +data[i].brand_name+" </a>";                                    
                    } 
                    html+=listr;
                    $(".clikbr").html(html);
               }
        });

html:

<span class="clikbr"></span>

javascript:

 function ch(){
        //方法能触发
        //添加样式
        $(this).addClass("on");  //这种方法不行    
        $(this).addClass("hoverWidgetactive").siblings().removeClass("hoverWidget active");  //也实现不了,
        
        
    };

It seems that the tags added through ajax cannot be obtained. I don’t know how to get the tags

PHP中文网PHP中文网2686 days ago794

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-06-12 09:26:00

    Use event delegation

    $('.clikbr').on('click', 'a', function() {
         $(this).addClass("on");    
         $(this).addClass("hoverWidgetactive").siblings().removeClass("hoverWidget active");  
    });

    reply
    0
  • 高洛峰

    高洛峰2017-06-12 09:26:00

    //You can change it to this

    $.ajax({type:"post",url:"carbrand/findCarBrandHot",dataType:"json",success:function(data){
                    var html="<a class='on' href='' rel='nofollow'>不限</a> ";
                        var listr = "";                        
                        for(var i = 0; i < data.length; i++){                
                                listr+="<a class=''  title=''  onclick='ch()'>"
                                        +data[i].brand_name+" </a>";                                    
                        } 
                        html+=listr;
                        $(".clikbr").html(html);
                        //必須在這裡給<a>標籤綁定事件
                        $(".clikbr a").on("click",function(){
                            $(this).addClass("on");  
                                                                          
                         
                         
           $(this).addClass("hoverWidgetactive").siblings().removeClass("hoverWidget active");
                        });
                   }
            });

    reply
    0
  • Cancelreply