开发者

jQuery click event on 1000 divs, optimize approach?

I'm building a system for selling tickets to events. Right now there are about 1000 diffrent seats to cho开发者_开发技巧ose from as a visitor. Maby one day it will be up to 5000.

Right now I have a div for each spot and then some jQuery to reserv the spot with ajax. So that meens that I have about 1000 divs and more alarming my jQuery selector sets a click event on each div.

Is there a better approach on this?

I want to trigger ajax when a div is pressed, not reloading the page.


Use .delegate():

$("#container").delegate(".child", "click", function(){
    alert("Clicked!");
});

This way you'll make just one event that manages all the divs.


simply use jQuery delegation method:

$('.theater').delegate('.seat','click',function(event){
  var self = $(event.target);
  console.log(self);
  // self is the '.seat' element that has been clicked.
});


Use "event delegation", i.e. bind the click event once, not to each individual div but to the div that surrounds your 1,000 divs. In the handler, you can retrieve the element for the div that was clicked, via the "event" object passed into your handler.


The approach is called event delegation and is as Ash explained. jQuery has a couple of methods to help here. live() and the newer delegate() http://api.jquery.com/delegate/ which is a bit more precise.

So you bind one click event to an element that is aparent of all the divs you are interested in and a click on them bubbles up the DOM to be captured by the parent. At which point you can do what you need to.


You might want to check this SO thread, it could be useful to you. From your post it's hard to tell, but an image map might be an option for you in this case. Using JQuery hover with HTML image map

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜