重构JS函数

时间:2018-03-25 21:51:05

标签: javascript function refactoring

我需要一些意见,我怎么能在没有jQuery的情况下重新输入这个函数呢?

// Where the registerUser mutation get's initiated - on form submit
onSubmit={() => {
    this.props.registerUser(values);
    // the error could be caught here but I don't want this in the UI - I'd rather keep all this outside
}}

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找以下内容:

'use strict';
const cards =document.querySelectorAll('.card')

function handleEvent() {
    if(this.classList.contains('open') || this.classList.contains('show')) {
        return;
    }
    this.classList.toggle('open')
    this.classList.toggle('show')
    openedCards.push(this)
    beginGame = true
}

cards.forEach(function(el) {
    el.addEventListener('click', handleEvent)
})

答案 1 :(得分:0)

由于cards可以是多个,你可以这样做。
我还为每张卡添加了onclick个事件:



var openedCards = [];
var beginGame = false;

function matchedCards() {
  const cards = (document).getElementsByClassName("card");
  for (var i = 0; i < cards.length; i++) {
    if (!cards.item(i).className.includes("open show")) {
      cards.item(i).className += " open show";
      openedCards.push(cards.item(i));
      beginGame = true;
    }
  }
  console.log(openedCards, beginGame);
}

function toggleCard(element) {
  if (!element.className.includes("open show")) {
    element.className += " open show";
    openedCards.push(element);
    beginGame = true;
  } else {
    const idx = element.className.indexOf("open show");
    const className = element.className.slice(0, idx) + element.className.slice(idx+9);
    element.className = className.trim();
  }
  console.log(openedCards, beginGame);
}
&#13;
.show {
  color: orange;
}
&#13;
<div class="card" onclick="toggleCard(this)">1</div>
<div class="card" onclick="toggleCard(this)">2</div>
<div class="card open show" onclick="toggleCard(this)">3</div>

<button onClick="matchedCards()">Show</button>
&#13;
&#13;
&#13;