js 怎如何给力下面的a标签全都加上个点击事件

js 怎如何给力下面的a标签全都加上个点击事件,第1张

var aLink=document.getElementsByTagName("a"含桥行谈哗)

for(i=0i<aLink.lengthi++){

aLink[i].onclick=show }

function show()

{

//消中do something

}

插入html代码后要重新绑定事件

近团仿日工作当中,需要对由jquery动态生成的标签添加一些事件效果。

最初的做法是在页面载入时调用事件监听如下:

Js代码

1.$(document).ready(function(){

2. $("a.keyWord1").hover( 3.function(){ 4. $(this).css("text-decoration","underline") 5. $(this).css("color","#fc9b3f") 6.},

7.function(){ 8.$(this).css("text-decoration","none") 9.$(this).css("color","") 10.}

11.)

12.})

$(document).ready(function(){

$("a.keyWord1").hover(

function(){

$(this).css("text-decoration","underline")

$(this).css("color","#fc9b3f")

},

function(){

$(this).css("text-decoration","none")

$(this).css("color","")

}

)

})本意是,当鼠标移动到a标签时触发hover效果。但是最终一点发应也没有,当然以上的代码没有问题,我在其它地方是可以使用的。

后来对比了其它地方用到这段代码的标签,发现我当前的a标签是通过jquery动态生成的,而不是后台生成的,所以思考可能是由于jquery在页面加载绑定事件时,由于我的后来动态生成的a标签还不存在,所以事件绑定自然就不成立!桥汪当然一点反应也没有!

找到问题,就开始找解决方案:

方案如下(不是很完美)

在动态生成标签后,添加如下代码:

Js代码

1.$("a.keyWord1").bind("mouseover",function(){

2. $(this).css("text-decoration","underline") 3. $(this).css("color","#fc9b3f") 4.

5. })

6.$("a.keyWord1").bind("mouseout",function(event){ 7.//阻止事件冒泡 8. event.stopPropagation()

9. $(this).css("text-decoration","none") 10. $(this).css("color","#06F") 11.$(this).unbind() 12. })

$("敏或仔a.keyWord1").bind("mouseover",function(){

$(this).css("text-decoration","underline")

$(this).css("color","#fc9b3f")

})

$("a.keyWord1").bind("mouseout",function(event){

//阻止事件冒泡

event.stopPropagation()

$(this).css("text-decoration","none")

$(this).css("color","#06F")

$(this).unbind()

})

上面的代码意思是,对a标签,且class=keyWord1的标签进行事件的绑定!

这样就达到我的目的!


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11995512.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存