onClick在p标签上无法正常工作 [英] onClick does not work properly on p tag
本文介绍了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标签上无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文