簡體   English   中英

無法將函數作為值傳遞給setAttribute

[英]Can't pass a function as a value to setAttribute

我有一些工作的SVG代碼,通過在形狀上設置屬性來處理鼠標事件:

function plot() {
  ...
  shape.setAttributeNS(null, "onmouseover", "popup_on (evt,"+sindex+","+month+")");
  shape.setAttributeNS(null, "onmouseout",  "popup_off(evt,"+sindex+")");
}

但是,我需要更改此代碼,因為popup_onpopup_off不再是靜態函數,並且需要大量上下文,具體取決於它們的調用位置。 我通過定義一個閉包,並將一個函數名稱作為屬性值來處理它:

function plot(popup_on, popup_off) {
  ...
  shape.setAttributeNS(null, "onmouseover", popup_on  + "(evt,"+sindex+","+month+")");
  shape.setAttributeNS(null, "onmouseout",  popup_off + "(evt,"+sindex+")");
}

但是,這不起作用 - 彈出代碼永遠不會被觸發。 如果我檢查Firebug或Dragonfly中的'shape'屬性,它們似乎是正確的。 'shape'具有'onmouseover'和'onmouseout'屬性,屬性的值是popup_onpopup_off函數的完整源文本:

onmouseover=function popup_on(evt, sindex, month) {
  ...
} 

但這些功能實際上並沒有運行。 知道我做錯了什么嗎? 謝謝。

UPDATE

感謝所有的反饋。 馬克的答案不起作用; 'function'被標記為語法錯誤。 'popup_on'和'popup_off'不是字符串 - 它們實際上是閉包中的函數。 不過,Sime和Erik的答案都有效,但有一個問題。

如果我將代碼更改為:

shape.addEventListener("mouseover", function() {popup_on (evt, sindex, month);}, false);

然后firebug抱怨說'evt'在嘗試執行popup_on (鼠標點擊時)是未定義的。 如果我將evt改為window.evtevt || window.evt evt || window.evt ,然后我沒有收到此錯誤,但我仍然無法訪問彈出處理程序中的事件:

   // popup handler in closure
   o["popup_on"] = function(evt, sindex, month) {
      // both evt and window.evt are undefined on entry
      evt = evt || window.evt;
      // so evt is still undefined, but...
      ...
      // I need to do this
      var upright = (evt.clientY >= cy);

知道為什么嗎? 謝謝。

UPDATE2

好的 - 修好了。 答案是:

shape.addEventListener("mouseover", function(evt) {popup_on (evt, sindex, month);}, false);
shape.addEventListener("mouseout",  function(evt) {popup_off(evt, sindex);}, false);
popup_on  + "(evt,"+sindex+","+month+")"

被視為“函數popup_on加上字符串'(evt,'再加上sindex plus的值......)

它不被解釋為構建函數調用。

如果你需要動態構建它的參數,你應該做更多的事情

shape.setAttributeNS(null, "onmouseout",  function() {
    popup_off(evt,sindex);
});

為什么不使用shape.addEventListener("mouseout", function() {...}, false) 請看這里的一些例子。

如果你想在你的函數中將事件對象命名為'evt',你可以命名它(你可以給它任何你想要的名字),如下所示: shape.addEventListener("mouseout", function(evt) {...}, false)

否則,事件變量默認在偵聽器函數中名為“event”,而不是“evt”。 這是一些混亂的根源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM