I'm trying to find the best way to provide some information to ajax handlers from html markup. The scenario is:
for i=0; i<5; i++
print <div class="clickable"></div>
Let's say that div will be clicked to add a product to a shopping cart. Like
$('.clickable').click(function{
cart.add(this.somethind);
})
I would like to transmit to that handler the unique sql id of that product clicked.
1) one ideea would be to add an attribute to that div, and store the information there. what do you think about this ideea?
2) is there any other way开发者_StackOverflow社区 to achive this, without using html markup?
info: Client side-jquery, Server side-PHP, not xml-xsl transformation used.
Thanks!
There is a jQuery metadata plugin just for those scenarios
<?php
print '<div class="clickable {id: 1}"></div>';
// or (HTML5-like)
print '<div class="clickable" data-id="1"></div>';
?>
// jQuery
$('.clickable').click(function{
cart.add($(this).metadata().id);
})
There are several other ways of providing metadata, check out project page
You could store it using jquery's data on the div.
$('.clickable').click(function{
cart.add(jQuery.data($(this), "id"));
});
EDIT
In response to your comment use this data link:
You could have you id as an HTML5 attribute:
<?php
print '<div class="clickable" data-id="1"></div>';
?>
Then you would access that id using data this way:
$('.clickable').click(function{
cart.add($(this).data("id"));
});
Note that this requires jquery 1.4.3 and above to work.
精彩评论