【问题标题】:onclick added with Tampermonkey is not calling the function?用 Tampermonkey 添加的 onclick 是不是调用函数?
【发布时间】:2013-05-18 05:44:34
【问题描述】:

如果我使用 Tampermonkey 以编程方式创建 div:

HTML:

<div onclick="myfunc()"/>

脚本:

function myfunc() { alert("clicked"); }

然后点击div; myfunc 在我的脚本中没有被调用。

我怎样才能让它工作?

(我使用 TM/jQuery 将 div 添加到页面,我想为其附加一些功能。我假设我必须将 HTML 中的函数调用重定向到正确的位置。我也使用 GM_函数,所以我不能直接插入代码。)

【问题讨论】:

    标签: javascript jquery onclick tampermonkey


    【解决方案1】:

    为“window”对象中的函数分配一个字段

    // ==UserScript==
    // @name        Content Script Example, grant none
    // @grant       none
    // ==/UserScript==
    
    function helper() {
        alert('helper');
    }
    
    window.helper2 = helper;
    
    element.innerHTML = "<button onclick='window.helper2()'>Click Me</button>" ;
    

    致谢:https://wiki.greasespot.net/Content_Script_Injection

    【讨论】:

      【解决方案2】:

      问题在于,由于您将属性设置为字符串,因此它正在评估目标页面范围内的字符串,该范围没有myfunc 函数。 myfunc 位于用户脚本范围内。

      作为一般规则,无论如何你都应该never use onclick,但这对于用户脚本来说是三倍。

      使元素易于选择,例如:

      <div id="gmMyDiv"></div>
      


      然后,要么使用the addEventListener() method,像这样:

      function myfunc (zEvent) {
          alert ("clicked"); 
      }
      
      var myDiv   = document.querySelector ("#gmMyDiv");
      if (myDiv) {
          myDiv.addEventListener ("click", myfunc , false);
      }
      


      或者因为您使用的是 jQuery:

      function myfunc (zEvent) {
          alert ("clicked"); 
      }
      
      $("#gmMyDiv").click (myfunc);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-11
        • 2021-03-07
        • 1970-01-01
        • 1970-01-01
        • 2013-03-18
        • 2021-12-17
        相关资源
        最近更新 更多