开发者

The onclick method gets executed when I am declaring it

开发者 https://www.devze.com 2023-03-07 21:29 出处:网络
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 t

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>  
&开发者_运维问答lt;/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});
}


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消