开发者

data to javascript handler

开发者 https://www.devze.com 2023-02-02 14:54 出处:网络
I\'m trying to find the best way to provide some information to ajax handlers from html markup. The scenario is:

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.

0

精彩评论

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

关注公众号