Convert javascript array handling to jQuery -
i'm doing javascript assignment , have learned can in jquery if wish, rather vanilla javascript. thought i'd give go see it's like.
this contents of javascript function:
rowsarray = $("#table1 tr"); (i=0;i<rowsarray.length;i++){ numseatsinrow = rowsarray[i].getelementsbytagname("img").length; // discovers number of seats in row [i] for(j=0;j<numseatsinrow;j++) { // loops round once each set in row [i] var currentseat = rowsarray[i].getelementsbytagname("img")[j]; currentseat.setattribute("id","row" + + "seat" + j); currentseat.onmouseover = function(){this.src = "images/taken.gif"}; currentseat.onmouseout = function(){this.src = "images/available.gif"}; currentseat.onclick = function() { this.src = "images/mine.gif"; this.onmouseover = null; this.onmouseout = null; document.getelementbyid("mytickets").innerhtml += this.id; } }
as can see, started converting jquery first line, got stuck :)
the code works is, figure there must more elegant way of doing in jquery. tried using $.each selectors or syntax wrong , didn't work. have vague idea how works 1d array, i'm not clear on how iterate through items in nested arrays i.e. array[x][y].
the function creates , moves through 2d array changing id , mouse events of set of images.
any thoughts appreciated :)
it can improved further, work:
$("#table1 tr").each(function(i) { $(this).find("img").each(function(j) { this.id = "row" + + "seat" + j; $(this).hover(function() { this.src = "images/taken.gif"; }, function() { this.src = "images/available.gif"; }) .click(function() { var img = this; this.src = "images/mine.gif"; $(this).unbind("mouseenter mouseleave"); $("#mytickets").html(function(i, h) { return h + img.id; }); }); }); });
using .each()
, index passes first parameter callback shortens bit (you don't need own i
, j
, they're there) rest jquery conversion, e.g. .hover()
mouse entering/leaving , .unbind()
remove handlers later.
here's bit more verbose much more efficient version using .delegate()
:
$("#table1 tr").each(function(i) { $(this).find("img").each(function(j) { this.id = "row" + + "seat" + j; }); }); $("#table1").delegate("tr img", "click", function() { var img = $(this).addclass("mine").add("src", "images/mine.gif"); $("#mytickets").html(function(i, h) { return h + img.attr("id"); }); }).delegate("tr img:not(.mine)", "mouseenter", function() { this.src = "images/taken.gif"; }).delegate("tr img:not(.mine)", "mouseleave", function() { this.src = "images/available.gif"; });
this attaches 3 handlers <table>
, listens events bubble up, rather attaching 3 handlers per image, it's cheaper on page load side, , and infinitesimal difference on runtime side.
Comments
Post a Comment