A
A
Andrey Kirin2017-11-01 16:01:22
JavaScript
Andrey Kirin, 2017-11-01 16:01:22

How to replace jQuery HTML with data from an array?

Due to insufficient knowledge, I have been racking my brain for 2 days on how to implement this. There is an array:

var array = [
   {id:1,name:"name1",img:"/images/img1.jpg",url:"http://url.ru/1"},
   {id:2,name:"name2",img:"/images/img2.jpg",url:"http://url.ru/2"}
];

Using jQuery, you need to find tags in html with attributes like data-price="{'1','name'}" and substitute values ​​there based on the fact that 1 is the value of the "id" attribute and the second value is the name of the array cell. Accordingly, the following should turn out:

{'1', 'name'} = name1

{'2', 'img'} = /images/img2.jpg

Before that, I used a simple construction, but now I need to use an array.

jQuery('.name').html('Николай');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
one_day, 2017-11-01
@AWKirin

var id, name, img, url;
var array = [
   {id:1,name:"name1",img:"/images/img1.jpg",url:"http://url.ru/1"},
   {id:2,name:"name2",img:"/images/img2.jpg",url:"http://url.ru/2"}
];

var d = $('div').data('price');
var arr = d.split("'");

$.each(array,function(index,value){
  if (arr[1] == value["id"]){
    id = value["id"];
    name = value["name"];
    img = value["img"];
    url = value["url"];
      };
  console.log('id: ' + id + '; name: ' + name + '; img: ' + img + '; url: ' + url);
});

D
Dark_Scorpion, 2017-11-01
@Dark_Scorpion

Just loop through the array, substituting data into your script from the current value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question