onClick在p标签上无法正常工作

编程入门 行业动态 更新时间:2024-10-25 16:19:36
本文介绍了onClick在p标签上无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想将click事件绑定到每个<p>,但似乎无法正常工作.

I want to bind a click event to every <p> but it does not seem to work properly.

运行脚本时,我立即收到三个警报.我只想在单击三个<p>'中的任何一个时获得它们.

When I run the script I instantly get three alerts. I only want to get them when clicking any of the three <p>'s.

有人可以告诉我我在做什么错吗?

Can anyone tell me what I'm doing wrong?

对,这就是它的样子. HTML就是应该的:<p class="special">text text text</p>等

Sry this is what it looks like. The HTML is just as it should: <p class="special">text text text</p> etc

(function () { var myFunction = function (theP) { alert(theP.id) } window.onload = function () { var pTags = document.getElementsByTagName('p'), pLength = pTags.length, i; for (i = 0; i < pLength; i += 1) { if(pTags[i].className == 'special'){ pTags[i].onClick = myFunction(pTags[i]); } }; } })();

Ps.我不能使用jQuery atm

Ps. I cannot use jQuery atm

推荐答案

感谢所有答案.非常感谢! 我重写了自己的脚本并按以下方式解决了它: 看起来如何?

Thanks for all answers. Much appreciated! I rewrote my own script and solved it like this: How does that look?

(function () { var myFunction1 = function (theP) { theP.onclick = myFunction2; }, myFunction2 = function(){ alert('hello world') } window.onload = function () { var pTags = document.getElementsByTagName('p'), pLength = pTags.length, i; for (i = 0; i < pLength; i += 1) { if(pTags[i].className == 'special'){ myFunction1(pTags[i]); } } } })();

更多推荐

onClick在p标签上无法正常工作

本文发布于:2023-11-11 18:41:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法正常   标签   工作   onClick

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!