代码之家  ›  专栏  ›  技术社区  ›  Ghasem

使用包含参数的函数更改onclick操作

  •  1
  • Ghasem  · 技术社区  · 9 年前

    在我的示例HTML代码中,我得到了一些带有默认功能的按钮,用于更改文本和样式 onclick 事件:

    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    
    <script>
    function changeText(id) {
        id.innerHTML = "Ouch!";
        id.style.color="red";
        id.onclick= again(this);
    }
    
    function again(id) {
        id.innerHTML = "Again!";
        id.style.color=#FF0000;
    }
    </script>
    

    我正在尝试改变 一次点击 默认函数结束时的事件:

    id.onclick= again(this);
    

    但这行不通;

    这是 jsfiddle link

    我尝试过解决方案 this question this one

    这个:

     id.onclick = function(this) { id.innerHTML = "Again!"; id.style.color=#FF0000; }
    

    这是:

     id.setAttribute( "onclick", "javascript: again(this);" );
    

    但它们都不管用。

    注意我需要 this 作为要发送到函数中的参数。

    我需要一个 javascript 解决方案不是 JQuery

    我做错了什么?

    3 回复  |  直到 8 年前
        1
  •  0
  •   Marcos Casagrande    9 年前

    您的代码有一些语法错误, id.style.color=#FF0000; ,十六进制值应为字符串。 id.style.color="#FF0000";

    在这一行中:

    id.onclick = again(this);
    

    你打电话给 again 功能&将返回值指定给 id.onclick 。如果要分配函数,只需使用 id.onclick = again

    这是您的代码,只做了一些小修改。

    function changeText(element) {
        element.innerHTML = "Ouch!";
        element.style.color="red";
        element.onclick = again; //Assign "again" function.
    }
    
    function again() {
        //this is the clicked element.
        this.innerHTML = "Again!";
        this.style.color="#FF0000";
    }
     button {
      font-size:20px;
      color:#0C6C89;
    }
    <!DOCTYPE html>
    <body>
    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    <button onclick="changeText(this)">Hit Me!</button><br>
    </body>
        2
  •  0
  •   Felipe    9 年前

    尝试以下操作:

    id.onclick= function onclick(event){again(this);}
    
        3
  •  -1
  •   dexhering    9 年前

    如果需要低耦合,可以这样做:

    function changeText(id) {
        id.innerHTML = "Ouch!";
        id.style.color= "red";
        // send the id
        id.onclick= again(id);
    }
    
    function again(id) {
        id.innerHTML = "Again!";
        id.style.color = "#FF0000";
    }
    
    推荐文章