【问题标题】:Javascript Flashcard Studying AppJavascript抽认卡学习应用
【发布时间】:2014-09-07 05:04:37
【问题描述】:

大家好,我正在尝试创建一个简单的学习应用程序,其工作方式类似于用于学习的闪存卡。所以卡片的正面会有问题,背面有答案,但是是数字的。我在 JavaScript 中完成这一切,并计划在 UI 中使用 HTML 和 CSS,因为这是我所知道的,我对编码非常陌生。这就是我目前所拥有的

//User creates math object to study math
var mathObj = {
    "1+1": 2,
    "1+2": 3
}

//User creates Spanish object to study Spanish
var SpanishObj = {
    "Amigo": "Friend",
    "Agua": "Water"
}

//Function that is used to add key value pairs to a object
function addKeyVal(obj, key, val){
    obj[key] = val;
}

addKeyVal(mathObj,"1+3", 4);

//Function that tests the user
function testUser(obj){

objKeys = Object.keys(obj);
answer = obj[objKeys[2]];

var userResponse = prompt(objKeys[2]);

    if ( userResponse == answer) {
        alert("Correct");
    } else{
        alert("Incorrect");
    };
};

testUser(mathObj);

我的第一个问题是我是否正确地解决了这个问题?那就是我应该使用对象而不是键值对数组(刚刚发现这些)?为了帮助提供更清晰的答案,我想在未来添加一个关键功能是让用户能够随机化他们收到问题的顺序。最后一个问题是如何让用户创建自己的对象/数组?

【问题讨论】:

    标签: javascript html arrays object


    【解决方案1】:

    我会这样做,虽然 alert 作为反馈是一个糟糕的解决方案(非常烦人),但请尝试以 html 形式提供或使用 console.log()

    // default object for a flash-card library
    function fc () {
      this.cards = {};
    }
    
    // clean input from tabs, spaces, upper-cases
    // you can add functionality to make it better
    fc.prototype.simplify = function ( val ) {
      return val.toLowerCase().trim();
    }
    
    // add to library an item
    fc.prototype.add = function ( key, val ) {
      key = this.simplify( key );
      val = this.simplify( val );
      this.cards[ key ] = val;
    }
    
    // check the right value for the key
    fc.prototype.check = function ( key, val ) {
      key = this.simplify( key );
      val = this.simplify( val );
    
      if ( this.cards.hasOwnProperty( key ) && this.cards[ key ] === val ) {
        return true;
      }
      return false;
    }
    
    // test all values in order
    fc.prototype.test = function () {
      for (var key in this.cards) {
        var guess = prompt('and a Spanish word for "' + key + '"' );
        if ( this.check( key, guess ) ) {
          alert( 'right' ); // console.log( 'right' )
        } else {
          alert( 'wrong' ); // console.log( 'wrong' )
        }
      }
    }
    
    
    
    // making a spanish cards stack
    var spanish = new fc();
    
    // adding cards
    spanish.add( 'Friend', 'Amigo' );
    spanish.add( 'Water', 'Agua' );
    
    
    // starting the test
    spanish.test();
    

    【讨论】:

    • 非常感谢 Nik,您添加键和值以及检查解决方案的方式比我的要好得多。现在我唯一剩下的问题是如何让用户通过 HTML 创建新卡片我是否只需将 html 元素映射到 onclick =“fc(this)” 以便用户创建自己制作的新对象,如果他们想要研究他们自己的独特对象。
    • 添加在下面。你可以这样做(不是 fc(this) - 因为那没有任何意义),但最好尽可能多地将 js 与 html 分开
    【解决方案2】:

    从页面添加(以及更多):

    <!DOCTYPE html>
    <html lang="en">
    <body>
    
    
      <ul id="tests"></ul>
    
      <button id="btn-add">Add test</button>
      <button id="btn-save">Save tests</button>
      <!-- <button id="btn-load">Load tests</button> -->
      <button id="btn-clear">Clear storage</button>
    
      <div id="div-result"></div>
      <div id="div-total"></div>
    
      <script type="text/javascript">
    
    (function ( document, window ) {
    
      var result = document.getElementById('div-result')
        , total = document.getElementById('div-total');
    
      // default object for a flash-card library
      function fc() {
        this.cards = {};
      }
    
      // clean input from tabs, spaces, uppercases
      fc.prototype.simplify = function ( val ) {
        if ( val !== null ) {
          return val.toLowerCase().trim();
        }
        return null;
      }
    
      // add to library an item
      fc.prototype.add = function ( key, val) {
        key = this.simplify( key );
        val = this.simplify( val );
        if ( key !== null && val !== null ) {
          this.cards[key] = val;
        }
      }
    
      // check the right value for the key
      fc.prototype.check = function ( key, val ) {
        key = this.simplify( key );
        val = this.simplify( val );
    
        if ( this.cards.hasOwnProperty( key ) && this.cards[ key ] === val ) {
          return true;
        }
        return false;
      }
    
      // test all values in order
      fc.prototype.start = function () {
        var rights = 0
          , wrongs = 0;
    
        result.innerHTML = '';
        total.innerHTML = '';
    
        for (var i in this.cards) {
          var guess = prompt('and a Spanish word for "' + i + '"' );
          if ( this.check( i, guess ) ) {
            result.innerHTML += 'Right: ' + i + ' &rarr; ' + this.cards[ i ];
            rights++;
          } else {
            result.innerHTML += 'Wrong: ' + guess + ', ' + i + ' &rarr; ' + this.cards[ i ];
            wrongs++;
          }
          result.innerHTML += '<br>';
        }
        total.innerHTML = 'Right answers: ' + rights + '<br>Wrong answers: ' +  wrongs ;
      }
    
    
    
    
    
    
    
    
    
      var app = ( function ( document, window ) {
        // declare some references, variables    
        var tests =  {}
          , el = document.getElementById('tests');
    
         function addTest () {
          var name = prompt('test name?');
          if ( name !== null ) {
            tests[ name ] = new fc();
            render();
          }
        }
    
        // register some events
        function registerEvents () {
          document.getElementById('btn-add').addEventListener( 'click', addTest, false );
          document.getElementById('btn-save').addEventListener( 'click', save, false );
          // document.getElementById('btn-load').addEventListener( 'click', load, false );
          document.getElementById('btn-clear').addEventListener( 'click', clear, false );
        }
    
        // render function
        function render () {
          var li = undefined
            , linkAdd = undefined
            , linkStart = undefined
            , docFrag = document.createDocumentFragment();
    
          // clear the dom
          while (el.firstChild) {
              el.removeChild( el.firstChild );
          };
          el.innerHTML = '';
    
          for ( var i in tests) {
            li = document.createElement( 'li' );
            li.innerHTML = i; // test name
    
            li.appendChild( document.createTextNode(' -> ') );
    
            // btn start test
            btnStart = document.createElement( 'button' );
            btnStart.setAttribute('data', i );
    
            btnStart.addEventListener( 'click', function( e ){
              var my = this.getAttribute( 'data');
              tests[ my ].start();
            }, false );
    
            btnStart.textContent = 'Start test';
            li.appendChild( btnStart );
    
            // btn add item to the test
            btnAdd = document.createElement( 'button' );
            btnAdd.setAttribute('data', i );
    
            btnAdd.addEventListener( 'click', function( e ){
              var my = this.getAttribute( 'data');
              tests[ my ].add( prompt( 'key' ), prompt( 'value' ));
            }, false );
    
            btnAdd.textContent = 'Add item';
            li.appendChild( btnAdd );
    
            // btn remove test
            btnRemove = document.createElement( 'button' );
            btnRemove.setAttribute('data', i );
    
            btnRemove.addEventListener( 'click', function( e ){
              var my = this.getAttribute( 'data');
              delete tests[ my ];
              render();
            }, false );
    
            btnRemove.textContent = 'Remove test';
            li.appendChild( btnRemove );
    
            docFrag.appendChild( li );
          };
    
          el.appendChild( docFrag );
        }
    
        // save tests to localstorage
        function save () {
          var data = JSON.stringify( tests );
          console.log( data );
          localStorage.setItem( 'tests', data );
        }
    
        // load tests form localstorage
        function load () {
          var saved = localStorage[ 'tests' ] || false;
          if ( saved ) {
            var data = undefined;
            data = JSON.parse( localStorage.getItem( 'tests' ) );
            console.log( data );
    
            // initialize test objects with loaded data
            for( var i in data ) {
              tests[ i ] = new fc();
              for ( var j in data[ i ] ) {
                tests[ i ][ j ] = data[ i ][ j ];
              }
            }
            render();
          } 
        }
    
        function clear () {
          localStorage.clear();
          tests = [];
          render();
        }
    
        // initialisation part
        registerEvents();
        load();
    
      } ) ( document, window );
    } ) ( document, window );
      </script>
    </html>
    

    【讨论】:

    • 这太棒了,非常感谢您的帮助!
    猜你喜欢
    • 2023-01-29
    • 2010-11-28
    • 2010-11-03
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多