붕어빵
붕어빵

Reputation: 31

How to use ' ' in javascript parameter

function nightDayHandler(self) {
  let selectorBody=document.querySelector('body');
  let selectorAll_A=document.querySelectorAll('a'); 
  
  function setColor(color) {
    let i=0;
    while(i<selectorAll_A.length){
      selectorAll_A[i].style.color='color';  // ' ' add
    i++;
  } }

  if (self.value==='night') {
    selectorBody.style.color='white';
    selectorBody.style.backgroundColor='black';
    setColor(powderblue);   // ' ' remove
    self.value='day';
  }
  else {
    selectorBody.style.color='black';
    selectorBody.style.backgroundColor='white';
    setColor(blue); // ' ' remove
    self.value='night';
  }   
}

Hi, I m studying javascript . I have a problem

I add ' ' to color

what is wrong with my code?

Upvotes: 0

Views: 66

Answers (2)

knosmos
knosmos

Reputation: 626

You can't just add those quotation marks like that. When you type "powderblue" without those quotation marks, JavaScript thinks it's a variable. Obviously this is not the case, as you want it to be a string.

Similarly, when you write "color", JavaScript thinks you're talking about a string. In this case, you want it to be a variable, since it is a function parameter.

Therefore, your code should look like:

function nightDayHandler(self) {
  let selectorBody=document.querySelector('body');
  let selectorAll_A=document.querySelectorAll('a'); 
  
  function setColor(color) {
    let i=0;
    while(i<selectorAll_A.length){
      selectorAll_A[i].style.color=color;  // note there are no quotes here
    i++;
  } }

  if (self.value==='night') {
    selectorBody.style.color='white';
    selectorBody.style.backgroundColor='black';
    setColor("powderblue");   // note the quotes
    self.value='day';
  }
  else {
    selectorBody.style.color='black';
    selectorBody.style.backgroundColor='white';
    setColor("blue"); // also quotes here so JS recognizes it as string
    self.value='night';
  }   
}

Upvotes: 1

D M
D M

Reputation: 7179

You don't want to do this:

function setColor(color) {
    // ...
    selectorAll_A[i].style.color = 'color';
    // ...
}

It will ignore your color parameter and try to se the selectorAll_A[i].style.color property to the string 'color'.

Instead, pass the value as a string and use the parameter name as the property value:

function setColor(color) {
    // ...
    selectorAll_A[i].style.color = color;
    // ...
}

setColor('blue');

Upvotes: 2

Related Questions