我可以在Javascript中使用数组更改大量HTML元素吗?

时间:2016-10-06 11:52:08

标签: javascript arrays switch-statement

我想在用户点击按钮时同时更改两个HTML元素的内容。元素的内容更改为基于随机数,然后将访问函数中定义的数组。

这就是我想要发生的事情,但是当我点击按钮(调用' deal()'功能)时,我目前没有得到任何改变。 / p>

有人可以给我任何建议吗?

这是我的代码 -

function createCard(){
   var shuffle = Math.floor(Math.random()*2) +1;

   var title = document.getElementById("cardTitle");
   var text = document.getElementById('cardText');
   var button = document.getElementById('cardButton');


   var cardTitle = ["Bacon", "Hot Dog Lattice"];
   var cardText = ['Frabdious Day', 'Calee, Calay',];

   var cardId = [cardTitle, cardText];


  switch (shuffle) {
    case 1:
      title.innerHTML = cardId(cardTitle[0]);
      text.innerHTML = cardId(cardText[0]);
      break;
    case 2:
      title.innerHTML = cardId(cardTitle[1]);
      text.innerHTML = cardId(cardText[1]);
      break; 
    default:
      title.innerHTML = "Oops";
      text.innerHTML = "Whoopsie";
  break;
 }
}


function deal(){
  createCard();
}

1 个答案:

答案 0 :(得分:0)

这可能是一个更好的解决方案:

function createCard(){
   var shuffle = Math.floor(Math.random()*2);
   var cards = [
     {
       title: "Bacon",
       text: "Frabdious Day"
     },
     {
       title: "Hot Dog Lattice",
       text: "Calee, Calay"
     }
   ];
  
  var shuffledCard = cards[shuffle];
  
  if (!shuffledCard){
    shuffledCard = {
       title: "Oops",
       text: "Whoopsie"
    }
  }
  
  var title = document.getElementById("cardTitle");
  var text = document.getElementById('cardText');
  var button = document.getElementById('cardButton');

  title.innerHTML = shuffledCard.title;
  text.innerHTML = shuffledCard.text;
  
 
}


function deal(){
  createCard();
}
<div id="cardTitle">Start value</div>
<div id="cardText">Start value</div>
<button id="cardButton" onClick="deal()">Deal</button>