开发者

Loop through name/values of an object to replace html in unique div's using jQuery

开发者 https://www.devze.com 2022-12-21 02:14 出处:网络
I\'m using the following cod开发者_JAVA百科e: $.each($dataObj, function(index, value) { $(index).html(value);

I'm using the following cod开发者_JAVA百科e:

  $.each($dataObj, function(index, value) {
    $(index).html(value); 
  });

Which of course does not work since $(index) is not a valid syntax.

Each index in the object corresponds to a a unique div-id on the webpage, so what I want to do is to replace the html in all of the div-id's listed in the dataObj with 'value'. How do I do that?


To make it valid jQuery syntax, simply add the 'ID' selector in front of it:

$.each($dataObj, function(index, value) {
  $('#' + index).html(value); 
});


You can use the $dataObj to access each.

Depending on it's contents, you might want:

$dataObj.eq(index).html(value);

However, it seems like you also might want to do an each loop like so:

$dataObj.each(function(i, value){
  $(this).html(value);
});

But even that's unnecessary if it's all the same value

$dataObj.html(value);

Would effectively loop through each element for you.

0

精彩评论

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

关注公众号