onclick方法在我声明它时被执行

The onclick method gets executed when I am declaring it

本文关键字:执行 声明 方法 onclick      更新时间:2023-09-26

我正试图声明一个onclick方法,该方法将调用一个函数,该函数将清除并重建显示被单击项目的更多详细信息的显示。问题是,我试图分配的onclick方法在分配时会被执行,所以我看到的只是其中一个项目的详细视图。

如果你删除i.node.onclick行,你会看到5个随机放置的项目,你可以悬停在上面,但不能点击。

HTML

<html>  
   <head>  
      <title>Raphael Play</title>  
      <script type="text/javascript" src="Raphael.js"></script>  
      <script type="text/javascript" src="Test.js"></script>  
      <style type="text/css">  
        #map 
        {  
           width: 500px;  
           border: 1px solid #aaa;  
        }  
      </style>  
   </head>  
   <body>  
      <div id="map"></div>  
   </body>  
</html>  

JavaScript

var map;
var items = new Array();
window.onload = function() 
{  
   map = new Raphael(document.getElementById('map'), 500, 500);  
   for(cnt = 0; cnt < 5; cnt++)
   {
      var x = 5 + Math.floor(Math.random() * 490);
      var y = 5 + Math.floor(Math.random() * 490);
      items[cnt] = new Item(x, y);
      var i = map.circle(items[cnt].x, items[cnt].y, 8).attr({fill: "#000", stroke: "#f00", title: items[cnt].name}); 
      i.node.onclick = detailView(items[cnt]);
   }
} 
function Item(x, y)
{
   this.x = x;
   this.y = y;
   this.name = "Item[" + x + "," + y + "]";
}
function detailView(dv)
{
   map.clear();
   map.circle(250, 250, 25).attr({fill: "#0f0", stroke: "#f00", title: dv.name});
}

首先需要一个辅助函数:

  function detailViewer(item) {
    return function() { detailView(item); };
  }

然后你可以像这样设置点击处理程序:

  i.node.onclick = detailViewer(items[cnt]);

helper函数为您构建了一个函数,当它被调用时,它将调用您的"detailView()"函数,传递与节点相关的项。正如您所注意到的,您的代码在执行初始化时被简单地调用了"detailView()"。"onclick"属性需要是一个函数本身,这就是我上面提出的helper函数将为您提供的。

您需要将i.node.onclick设置为一个函数。您将其设置为detailView(items[cnt]),运行该函数,然后将i.node.onclick设置为返回值(即undefined)。

您需要让detailView返回一个函数。

function detailView(dv){
  return function(){
    map.clear();
    map.circle(250, 250, 25).attr({fill: "#0f0", stroke: "#f00", title: dv.name});
  };
}