简体   繁体   English

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

[英]onClick does not work properly on p tag

I want to bind a click event to every <p> but it does not seem to work properly. 我想将click事件绑定到每个<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. 我只想在点击三个<p>'任何一个时获取它们。

Can anyone tell me what I'm doing wrong? 谁能告诉我我做错了什么?

Edit: Sry this is what it looks like. 编辑:Sry这就是它的样子。 The HTML is just as it should: <p class="special">text text text</p> etc HTML正如它应该的那样: <p class="special">text text text</p>

(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. PS。 I cannot use jQuery atm 我不能使用jQuery atm

Try replacing 尝试更换

pTags[i].onClick = myFunction(pTags[i]);

with

pTags[i].onClick = function() { myFunction(pTags[i]); }

You see, when you assign to the onClick of an object, you're copying the result of the expression to it. 您可以看到,当您分配给对象的onClick时,您正在将表达式的结果复制到它。 What your supposed to copy is a function to call when the p is clicked. 您应该复制的是在单击p时调用的函数。

Instead, you're running the command myFunction(pTags[i]) , which executes the alert() s, and takes the result of the function. 相反,您正在运行命令myFunction(pTags[i]) ,它执行alert() ,并获取函数的结果。 Now, since the function doesn't return anything, the value of the expression myFunction(pTags[i]) is undefined. 现在,由于函数不返回任何内容,因此未定义表达式myFunction(pTags[i])值。

And you take that value, and assign it to onClick . 然后你获取该值,并将其分配给onClick So basically what you've done is: 基本上你所做的是:

For each "special" paragraph: 对于每个“特殊”段落:

  1. Execute alert 执行alert
  2. Assign undefined to the paragraph's onClick . undefined分配给段落的onClick

myFunction would need to return a function for your code to work myFunction需要返回一个函数让你的代码工作

Below someone mentions an option that tries to create an inline function, but because closure binding happens with variables, not values, this will not work (The i in the code will be modified after including it in the function). 下面有人提到了一个尝试创建内联函数的选项,但是因为闭包绑定发生在变量而不是值上,所以这将不起作用(代码中的i在将其包含在函数中后进行修改)。

There are two obvious ways to create the function and have it work. 有两种显而易见的方法来创建函数并使其工作。 One is to create a per-handler function... The other is using this to get the element. 一种是创建一个per-handler函数......另一种是使用this来获取元素。

(function () {
    var myFunction = function (theP) {
            return function() {
                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]);

                }
        };
    }
})();

And with this 有了this

(function () {
    var myFunction = function () {
                alert(this.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;

                }
        };
    }
})();

The second format is the preferred format, as it uses much less memory to implement by the browser. 第二种格式是首选格式,因为浏览器使用的内存要少得多。

.onclick是区分大小写的,不是吗?

You are calling your function. 你在调用你的功能。 When you use the parenthesis you call your function. 当您使用括号时,您可以调用您的函数。

onclick requires a function reference: onclick需要一个函数引用:

You could modify your code this way: 您可以这样修改您的代码:

myFunction(theP){
 return function(){alert(theP.id)};
}

This would insure that your call returns a function reference instead of a value. 这将确保您的调用返回函数引用而不是值。

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]);
            }
        }
    }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM