weixin_33701294 2015-02-26 18:17 采纳率: 0%
浏览 47

Ajax表中的按钮链接

Please look at the ajax code below, As you can see, i have managed to make a button display in each table row, which is great, the issue is each button will only link ti the dataurl, I'm really needing to make it so that each button will link off to a different place, But only is the event is still available. E.g. if a row disappears i need the button to disappear? So the Increment feature wouldn't work.

Thanks Sam

Heres the ajax code

$.ajax({
    type: 'GET',
    crossDomain: true,
    dataType: 'json',
    url: 'api link for seatwave',
    success: function(json) {
        //var json = $.parseJSON(data);
        for (var i = 0; i < json.results.TicketGroups.length; i++) {
            var section = json.results.TicketGroups[i].TicketTypeName;
            var no = json.results.TicketGroups[i].Qty;
            var price = json.results.TicketGroups[i].
            Price;
            var button =
                "<button class='btn btn-info' data-url='LINK'>Click Here</button>";
            $("#tableid").append("<tr><td>seatwave</td><td>" + section +
                "</td><td>N/A</td><td>N/A</td><td>" + no +
                "</td><td>£"+price +
                "</td><td>" + button + "</td></tr>");
            $("#tableid").find(".btn.btn-info").click(function() {
                location.href = $(this).attr("data-url");
            });
        }
        sortTable();
    },
    error: function(error) {
        console.log(error);
    }
});
  • 写回答

2条回答 默认 最新

  • weixin_33697898 2015-02-26 18:27
    关注

    you are selecting all buttons every iteration of the for loop;

    //this line selects all elements with classes .btn.btn-info
    $("#tableid").find(".btn.btn-info")
    

    therefore once its done all your buttons will have the link of the last created button.

    it would be easier if instead of the line:

    var button = "<button class='btn btn-info' data-url='LINK'>Click Here</button>";
    

    you would wrap the button with a jQuery object, and attach the click handler to it:

    var button = $("<button class='btn btn-info' data-url='LINK'>Click Here</button>");
    button.click(function() {
         location.href = $(this).attr("data-url");
    }); 
    

    and when you add the button to the dom you can do it this way:

    //this will retrieve the html element from the jquery object
    "</td><td>" + button[0] + "</td></tr>"  
    
    评论

报告相同问题?