loop through AJAX response & divs, setting div values equal to AJAX values of same id

放肆的年华 提交于 2019-12-25 06:36:11

问题


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 divs 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!