javascript - 在一個(gè)a標(biāo)簽內(nèi)添加了一個(gè)單擊事件,想在時(shí)間里面給這個(gè)a標(biāo)簽添加類樣式
問題描述
在一個(gè)span標(biāo)簽里面有多個(gè)a標(biāo)簽,a標(biāo)簽是通過ajax實(shí)現(xiàn)的。想在a標(biāo)簽里面添加單擊事件,在他單擊的時(shí)候給這個(gè)a標(biāo)簽添加類樣式 ,同時(shí)刪除其他a標(biāo)簽類樣式
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(){//方法能觸發(fā)//添加樣式$(this).addClass('on'); //這種方法不行 $(this).addClass('hoverWidgetactive').siblings().removeClass('hoverWidget active'); //也實(shí)現(xiàn)不了, };
貌似通過ajax新增的標(biāo)簽獲取不到,不知道怎么獲取標(biāo)簽
問題解答
回答1:使用事件委派
$(’.clikbr’).on(’click’, ’a’, function() { $(this).addClass('on'); $(this).addClass('hoverWidgetactive').siblings().removeClass('hoverWidget active'); });回答2:
//你可以改成這樣
$.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>標(biāo)籤綁定事件 $('.clikbr a').on('click',function(){$(this).addClass('on'); $(this).addClass('hoverWidgetactive').siblings().removeClass('hoverWidget active'); }); }});
