开发者

jQuery - getting the id of the item selected

开发者 https://www.devze.com 2022-12-29 00:28 出处:网络
I have a basic jQuery selector question. Let\'s say I\'m parsing JSO开发者_JS百科N and generating a row of data for each item in my result set. On each item row, I want an action button. What is the

I have a basic jQuery selector question.

Let's say I'm parsing JSO开发者_JS百科N and generating a row of data for each item in my result set. On each item row, I want an action button. What is the best practice to script that button so its click action can reference the data specific to that row?

Starting with the block below, how do I generate a 'Click Me' button that when clicked will alert with its json data?

   $.getJSON(url,params,function(json){
    if(json.items){
        $.each(json.items, function(i, n){
            var item = json.items[i];


You could do this:

$.getJSON(url,params,function(json){
  if(json.items){
    $.each(json.items, function(idx, item){
      $("<button>Click Me</button>").click(function() {
        alert($(this).data("json");
      }).data("json", item).appendTo("body");
    });
  }
});
0

精彩评论

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