2

In my JavaScript I have an array of data stored in two ways

  • as an array of arrays data1[i++] = [id, url, val]

and

  • as array of objects data2[i++] = {id:id, url:url, val:val}

when I will output both arrays to the console I see all data which are correct.

Next I want to access them. For a first set of data I'm doing that:

  var total = data1.length;
      for (var j = 0; j < total; j++) {
        console.log(data1[j]);
      }

and then for second set of that

  var total = data2.length;
      for (var j = 0; j < total; j++) {
        console.log(data2[j].id + data2[j].gradient + data2[j].url);

      }

but if I want to use them (data from an object)

jQuery( "#' + data2[j].id + ' .banner-bg" ).css( "background-image",  data2[j].url );

it throws an error

Error: Syntax err or, unrecognized expression: # + data[j].id + .banner-bg

Where I have made a mistake?

3 Answers 3

7

You're just escaping your quotes wrong. Do this:

jQuery( '#' + data2[j].id + ' .banner-bg' ).css( "background-image",  data2[j].url );
Sign up to request clarification or add additional context in comments.

Comments

1

Your argument for jQuery wrong. Try this:

var arg = '#' + data2[j].id + '.banner-bg';
jQuery(arg).css( "background-image",  data2[j].url );

Comments

0

This:

jQuery( "#' + data2[j].id + ' .banner-bg" ).css( "background-image",  data2[j].url );

Should be this:

jQuery( "#" + data2[j].id + " .banner-bg" ).css( "background-image",  data2[j].url );

In the first the whole string including the reference to the array object ( data2[j].id ) is being parsed by jQuery.

Read more about JS operators here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.