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
PHP中文网
PHP中文网 2017-06-12 09:24:00
0
2
791

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中文网

认证高级PHP讲师

reply all(2)
左手右手慢动作

Use event delegation

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

//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");
                    });
               }
        });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!