how to access result property of Success function of jquery
I have a success
fun开发者_如何学编程ction of jQuery defined as:
success: function(result) {
var htmlString = [result];
for (i = 0; i < htmlString.length; i++) {
$('#MyGrid tbody').append('<tr><td><a href="#">' + htmlString[i].name+ '</a></td><td><a href="#" class="remove">Remove</a></td></tr>');
}
},
And an event handler bound with delegate
:
$('#MyGrid').delegate('a.remove', 'click', function() {
var name= ;$(this).closest('tr').find("td").eq(0).find('a').text();
var number = ; //here i need to access htmlString[i].number
alert(number);
}
How can I assign htmlString[i].number
to the number
variable?
there may be better ways but one way is to on the success
callback assign the result
to some global scope variable and access it in the delegate call
else you can do it this way assign the htmlString[i].number
to the rel
tag
success: function(result) {
var htmlString = [result];
for (i = 0; i < htmlString.length; i++) {
$('#MyGrid tbody').append('<tr><td><a rel="'+htmlString[i].number+'" href="#">' + htmlString[i].name+ '</a></td><td><a href="#" class="remove">Remove</a></td></tr>');
}
},
and in the delegate call
$('#MyGrid').delegate('a.remove', 'click', function() {
var name= $(this).closest('tr').find("td").eq(0).find('a').text();
var number = $('#MyGrid').delegate('a.remove', 'click', function() {
var name= $(this).closest('tr').find("td").eq(0).find('a').text();
var number = $(this).closest('tr').find("td").eq(0).find('a').attr('rel');
alert(number);
}
alert(number);
}
This seems like a perfect use case for .data()
:
/*snip */
for (i = 0; i < htmlString.length; i++) {
var $row = $('<tr><td><a href="#">' + htmlString[i].name + '</a></td><td><a href="#" class="remove">Remove</a></td></tr>');
$row.find("a.remove").data("number", htmlString[i].number);
$('#MyGrid tbody').append($row);
}
Then in your event handler:
$('#MyGrid').delegate('a.remove', 'click', function() {
var number = $(this).data("number");
alert(number);
});
Here's a working example: http://jsfiddle.net/BRZD7/
精彩评论