问题
Because of jQuery, I've been able to indulge my laziness to the max, but the real benefit has been spending most time on the good stuff and less on the tedious. I'd like to further that.
Currently, I'll have some HTML like so:
<div id="id1"></div>
<div id="id2"></div>
<div...
and so on.
Then, I'll call ajax
, expecting the object "ids" to be the same as the div ids like so:
$.ajax({
success: function (msg) {
$("#id1").text(msg.id1);
$("#id2").text(msg.id2);
$("#...
and so on.
Can this be reduced to a "one-liner"? Specifically, I don't know how to use the ids of the div
s in the response object array.
Many thanks in advance!
回答1:
Yes, it can, use the jQuery.each() method:
success: function (msg) {
jQuery.each(msg, function(key, value){
$('#' + key).text(value);
});
}
回答2:
If there's someway to separate your div's from other divs on your page you can do it like this
$('div[id^=id]').text(function(){ return msg[this.id] }); // <-- one liner just for you
Accessing properties of object can be done two ways..
msg.property
msg[property] // <-- this way is more flexible...
So your actually passing in each div's id as the property name
msg[id1] // etc..
来源:https://stackoverflow.com/questions/14408522/loop-through-ajax-response-divs-setting-div-values-equal-to-ajax-values-of-sa