亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

你能在一個數組中操作一個JS函數嗎?

你能在一個數組中操作一個JS函數嗎?

繁花如伊 2023-03-03 13:18:34
我有 JS 測驗,問題是從數組中隨機選擇的。我試圖用圖像(俱樂部徽章)替換每個問題,但保持答案格式不變。這可能嗎?如何實現?當前代碼如下:JavaScriptconst questions = [    {        question:  `What league do Manchester United play in?`,        answers: [            {text: 'Premier League', correct: true},            {text: 'Championship', correct: false},            {text: 'League One', correct: false},            {text: 'Scottish Premiership', correct: false}        ]    },    {        question: 'What league do Millwall play in?',        answers: [            {text: 'Premier League', correct: false},            {text: 'Championship', correct: true},            {text: 'League One', correct: false},            {text: 'Scottish Premiership', correct: false}        ]    },HTML:<div id="question"><img id="crest" src="assets/images/image1.png"></div>我已經在 JS 中創建了這些函數,但不知道如何讓它們在問題中運行function displayManutdCrest() {    document.getElementById('crest').src='assets/images/image2.png'}function displayMillwallCrest() {    document.getElementById('crest').src='assets/images/image3.png'}我只是在學習 JS,如果這沒有意義,我深表歉意
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

我認為這個問題是有道理的,可以說明一些有用的東西。您想要創建一種易于放大的方法。如評論中所述,您不想為每個問題編寫一個函數,這會使構建問題庫變得非常困難。您需要一個單一的功能來回答任何問題以及您需要的所有信息。那么函數只需要從題庫中讀取相應的信息即可。您可以添加另一個標簽,例如pict. 類似(非功能代碼):


const questions = [

{

    question:  `What league do Manchester United play in?`,

    pict: "assets/images/image2.png",

    answers: [

        {text: 'Premier League', correct: true},

        {text: 'Championship', correct: false},

        {text: 'League One', correct: false},

        {text: 'Scottish Premiership', correct: false}

    ]

},

{

    question: 'What league do Millwall play in?',

    pict: "assets/images/image3.png",

    answers: [

        {text: 'Premier League', correct: false},

        {text: 'Championship', correct: true},

        {text: 'League One', correct: false},

        {text: 'Scottish Premiership', correct: false}

    ]

},

...

];


function displayQuestion(q){

  // Choose question

  let i = ... ; //someRandomValue;

  let question = q[i];

  //

  document.getElementById('crest').src = question.pict;

}


displayQuestion(questions);


查看完整回答
反對 回復 2023-03-03
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號