James wrote:
I think a good way is to put the data into a separate JSON object and
give them a unique ID (eg. item01, item02...), and assign that ID
somewhere on the links to be clicked.

var productList = {
  'item01':{name:123-ABC, color:'red', price:9.99},
  'item02':{name:123-ABC, color:'blue', price:10.99},
  'item03':{name:456-DEF, color:'green', price:29.99}
}

$(".buy").click(function() {
     var id = $(this).attr("id");
     var product = productList[id];
     alert(product.name + ' ' + product.color + ' ' + product.price);
});


<img src="item01.jpg /><a href="." id="item01" class="buy">Buy Me!</
a><br />
<img src="item02.jpg /><a href="." id="item02" class="buy">Buy Me!</
a><br />
<img src="item03.jpg /><a href="." id="item03" class="buy">Buy Me!</
a><br />



On Feb 13, 10:35 am, Eric P <eric.maill...@gmail.com> wrote:
Hi,

I'm fairly new to jQuery (been using a few months now).  Binding event handlers 
to HTML objects via jQuery is awesome,
but I find myself struggling to find a solid (I.e., best practice) method for 
getting numerous arguments to the event
handler that are pertinent to the object that triggered the event.

For example, old method:
<script>
function buy(item, color, price) { ... }
</script>
...
<img src="item01.jpg /><a href="javascript:buy('123-ABC','red',9.99)>Buy 
Me!</a><br />
<img src="item02.jpg /><a href="javascript:buy('123-ABC','blue',10.99)>Buy 
Me!</a><br />
<img src="item03.jpg /><a href="javascript:buy('456-DEF','green',29.99)>Buy 
Me!</a><br />

jQuery method:
<script>
$(function() {
     $('.buy').click(function() { ... }
)};
</script>
...
<img src="item01.jpg /><a class="buy">Buy Me!</a><br />
<img src="item02.jpg /><a class="buy">Buy Me!</a><br />
<img src="item03.jpg /><a class="buy">Buy Me!</a><br />

So in the jQuery method, what is the best way to make the multiple arguments 
(that were previously in the inline HTML/JS
function call) available to the event handling function?

I've been limping along using various methods to get arguments to the event 
handling function (E.g., like sticking
values in an object's id field, etc.), but I'm at a loss when it comes to a solid way to 
"pass" numerous arguments to
the event handling function.

Thanks for reading,
Eric P.


James,
Your solution is elegant and robust. It fit the bill perfectly for what I was doing. I was about to use jQuery's data() method to attach values to HTML objects, but your solution is much easier to digest.

Thanks for the great insight!

RobG,
Good point. It's always good to work w/the mindset that not all will have JavaScript turned on. Fortunately, the functionality I'm building is for an administrative area for customers that must have JavaScript support to even log in.

donb,
Don't worry.  The code example I gave was merely an example to simplify the 
problem.  No $0.01 items for you!  ;)

Eric

Reply via email to