如何击败JavaScript条件之谜?

时间:2017-09-01 05:47:14

标签: javascript

我在php中使用foreach循环从mysql表加载数据。我使用从数据库加载的数据ID并将其应用于按钮值。

按钮有两种颜色,绿色和白色。按钮表示喜欢评论或帖子。

现有的总数量从6开始(div id =" total")

白色按钮

如果按钮1的颜色为白色并单击它,则总喜欢(6)将增加1.如果再次单击按钮1,则总喜欢(7)将减少1.

如果单击按钮1,按钮2和按钮3,则总喜欢(6)增加3(每个按钮1个)。如果再次点击按钮1,按钮2和按钮3,则总喜欢(9)将减少3.

益智

绿色按钮

如何实现这一点,单击绿色按钮时,总计(6)减少1,如果再次单击该按钮,则应增加1.与白色按钮不同。

如果单击绿色按钮3,5和6,则总计(6)应减少3.如果再次单击相同的按钮,则总计(6)增加3。

这是我的代码



var colorcode = "rgb(116, 204, 49)";
var buttonid = str;
var elem = document.getElementById(buttonid);
var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");

var initialtotal = parseInt(document.getElementById("total").innerHTML, 10);
var likes = new Array();

function showUser(str) {
  ////// 1st condition /////
  if (theCSSprop == colorcode) {

    if (likes[value] == 0 || !likes[value]) {
      likes[value] = 1;
    } else {
      likes[value] = 0;
    }
    var sum = 0;
    for (i = 0; i < likes.length; i++) {
      if (likes[i] == 1) {
        sum--
      }
    }

  }
  ////// 2nd condition /////
  else {
    if (likes[str] == 0 || !likes[str]) {
      likes[str] = 1;
    } else {
      likes[str] = 0;
    }

    var sum = 0;
    for (i = 0; i < likes.length; i++) {
      if (likes[i] == 1) {
        sum++
      }
    }

  }
  var tot = initialtotal + sum;

  document.getElementById("total").innerHTML = tot;

}
&#13;
<div id="total" style="width:100px;padding:50px 0px; background-color:whitesmoke;text-align:center;">6 </div>

<!---------------------------------------------------------------------------------------------------------------------->
<button id="5" value="5" onclick="showUser(this.value)">LIKE </button>

<button id="346" value="346" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>

<button id="128" value="128" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>

<button id="687" value="687" onclick="showUser(this.value)">LIKE </button>

<button id="183" value="183" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>

<button id="555" value="555" onclick="showUser(this.value)">LIKE </button>
<!---------------------------------------------------------------------------------------------------------------------->
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

不要将this.value传递给showUser(),而是传递this。这样,函数可以直接获取值和样式,而无需调用getElementById()(您没有传递ID)。然后你需要在函数内部设置theCSSprop,因此它是当前按钮的属性。

要使绿色按钮从增量到减量交替方向,您需要一个全局变量来记住上次调用该函数时所执行的操作。

此外,您不需要写if(likes[str] == 0 || !likes[str]),因为0是有效的。只需写下if(!likes[str])

var colorcode = "rgb(116, 204, 49)";

var likes = new Array();
var greenIncr = -1;

function showUser(elem) {
  var initialtotal = parseInt(document.getElementById("total").innerHTML, 10);
  ////// 1st condition /////
  var str = elem.value;
  var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
  if (theCSSprop == colorcode) {

    if (!likes[str]) {
      likes[str] = 1;
    } else {
      likes[str] = 0;
    }
    var sum = 0;
    for (i = 0; i < likes.length; i++) {
      if (likes[i] == 1) {
        sum += greenIncr;
      }
    }
    greenIncr = -greenIncr; // revese the direction of green button

  }
  ////// 2nd condition /////
  else {
    if (!likes[str]) {
      likes[str] = 1;
    } else {
      likes[str] = 0;
    }

    var sum = 0;
    for (i = 0; i < likes.length; i++) {
      if (likes[i] == 1) {
        sum++
      }
    }

  }
  var tot = initialtotal + sum;

  document.getElementById("total").innerHTML = tot;

}
<div id="total" style="width:100px;padding:50px 0px; background-color:whitesmoke;text-align:center;">6 </div>

<!---------------------------------------------------------------------------------------------------------------------->
<button id="5" value="5" onclick="showUser(this)">LIKE </button>

<button id="346" value="346" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>

<button id="128" value="128" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>

<button id="687" value="687" onclick="showUser(this)">LIKE </button>

<button id="183" value="183" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>

<button id="555" value="555" onclick="showUser(this)">LIKE </button>
<!---------------------------------------------------------------------------------------------------------------------->

答案 1 :(得分:0)

第一个天真的实现可能看起来像这样

&#13;
&#13;
trunk
&#13;
class Counter {
  constructor(initial) {
    this.initial = initial
    this.white = [false, false, false]
    this.green = [false, false, false]
  }

  changeGreen(index) {
    this.green[index] = !this.green[index]
  }

  changeWhite(index) {
    this.white[index] = !this.white[index]
  }

  get total() {
    return this.initial + this.white.reduce((total, current) => total + current, 0) + this.green.reduce((total, current) => total - current, 0)
  }
}

let counter = new Counter(6)

const render = counter => {
  document.querySelector('#total').innerHTML = counter.total
}

render(counter)

;['#first', '#second', '#third'].map((selector, index) => {
  document.querySelector(selector).addEventListener('click', e => {
    e.target.classList.toggle('pressed')
    counter.changeWhite(index)
    render(counter)
  })
})

;['#fourth', '#fifth', '#sixth'].map((selector, index) => {
  document.querySelector(selector).addEventListener('click', e => {
    e.target.classList.toggle('pressed')
    counter.changeGreen(index)
    render(counter)
  })
})
&#13;
.green {
  background: #00aa00
}

.pressed {
  border-style: inset
}
&#13;
&#13;
&#13;

但毕竟我已经完成了像

这样的事情

&#13;
&#13;
<div id="total">0</div>

<p>
  <button id="first">First</button>
  <button id="second">Second</button>
  <button id="third">Third</button>
  <button id="fourth" class="green">Fourth</button>
  <button id="fifth" class="green">Fifth</button>
  <button id="sixth" class="green">Sixth</button>
</p>
&#13;
class Counter {
  constructor(initial, strategy) {
    this.initial = initial;
    this.elements = [];
    this.strategy = typeof strategy === 'function' ? strategy : () => {}
  }

  addElement(content, type, next) {
    const element = {
      content: content,
      type: type,
      state: false
    };
    this.elements.push(element);
    return next(element, this.elements.length - 1);
  }

  toggleElementState(index) {
    this.elements[index].state = !this.elements[index].state
  }

  get total() {
    return this.strategy(this.initial, this.elements)
  }
}

const initialize = () => {

  Counter.WHITE = Symbol('white');
  Counter.GREEN = Symbol('green');

  const counter = new Counter(6, (initial, buttons) => {
    return initial +
      buttons.filter(button => button.type === Counter.WHITE).reduce((total, current) => total + Number(current.state), 0) +
      buttons.filter(button => button.type === Counter.GREEN).reduce((total, current) => total - Number(current.state), 0)
  });

  const render = counter => {
    document.querySelector('#total').innerHTML = counter.total
  };

  const createButton = (element, index) => {
    const button = document.createElement('button');
    button.setAttribute('data-id', index);
    button.classList.add(element.type === Counter.GREEN ? 'green' : 'none');
    button.textContent = element.content;
    document.querySelector('#buttons').appendChild(button)
  };

  const addButton = (type, ...selectors) => {
    selectors.forEach(selector => counter.addElement(selector, type, createButton));
  };

  render(counter);

  addButton(Counter.WHITE, '#first', '#second', '#third');
  addButton(Counter.GREEN, '#fourth', '#fifth', '#sixth');
  addButton(Counter.WHITE, '#first', '#second', '#third');

  document.querySelector('#buttons').addEventListener('click', function(e) {
    e.target.classList.toggle('pressed');
    counter.toggleElementState(parseInt(e.target.dataset.id));
    render(counter)
  })

};

document.addEventListener('DOMContentLoaded', initialize);
&#13;
.green {
  background: #00aa00
}

.pressed {
  border-style: inset
}
&#13;
&#13;
&#13;