The onclick method gets executed when I am declaring it

假装没事ソ 提交于 2019-12-12 23:34:12

问题


I am trying to declare an onclick method that will call a function that clears and rebuilds the display showing more detail on the item that was clicked. The problem is the onclick method I am trying to assign gets executed when I assign it so all I see is the detail view of one of the items.

If you remove the i.node.onclick line you see 5 randomly placed items that you can hover over but not click on.

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

回答1:


First you need a helper function:

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

Then you'd set the click handler like this:

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

The helper function builds you a function that will, when it's called, call your "detailView()" function, passing in the item related to the node. Your code as written simply called "detailView()" while performing the initialization, as you noticed. The "onclick" attribute needs to be a function itself, which is what the helper function I proposed above will give you.




回答2:


You need to set i.node.onclick to a function. You are setting it to detailView(items[cnt]) which runs that function then sets i.node.onclick to the return value (which is undefined).

You need to have detailView return a function.

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


来源:https://stackoverflow.com/questions/6111873/the-onclick-method-gets-executed-when-i-am-declaring-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!