Creating 26 alphabet letter buttons with the for loop and String.fromCharCode()

后端 未结 2 947
死守一世寂寞
死守一世寂寞 2021-01-28 07:46

here is some HTML Code as example:



<         


        
相关标签:
2条回答
  • 2021-01-28 08:16

    Try this.

    HTML

    <div id="buttonsHolder"></div>
    <div id="name"></div>  
    

    Javascript

    window.addEventListener( "load", function( windowLoadE ) {
        var p, letter, button, holder;
        holder = document.getElementById( "buttonsHolder" );
        for ( var i = 65; i <= 90; i++ ) {
            if ( i == 65 || i == 75 || i == 84 ) {
                p = document.createElement( "p" );
            }
            letter = String.fromCharCode( i );
            button = document.createElement( "button" );
            button.innerHTML = letter;
            button.setAttribute( "data-letter", letter );
            button.onclick = function( e ) { setLetter( this.getAttribute( "data-letter" ) ); };
            p.appendChild( button );
            if ( i == 74 || i == 83 || i == 90 ) {
                holder.appendChild( p );
            }
        }
    } );
    function setLetter( letter ) {
        var div = document.getElementById( "name" );
        div.innerHTML = div.innerHTML + letter;
    }
    

    This solution like @Arvind's, but I think better use attribute of html tag and set onclick with functions.

    window.addEventListener( "load", function( windowLoadE ) {
        var p, letter, button, holder;
        holder = document.getElementById( "buttonsHolder" );
        for ( var i = 65; i <= 90; i++ ) {
            if ( i == 65 || i == 75 || i == 84 ) {
                p = document.createElement( "p" );
            }
            letter = String.fromCharCode( i );
            button = document.createElement( "button" );
            button.innerHTML = letter;
            button.setAttribute( "data-letter", letter );
            button.onclick = function( e ) { setLetter( this.getAttribute( "data-letter" ) ); };
            p.appendChild( button );
            if ( i == 74 || i == 83 || i == 90 ) {
                holder.appendChild( p );
            }
        }
    } );
    function setLetter( letter ) {
        var div = document.getElementById( "name" );
        div.innerHTML = div.innerHTML + letter;
    }
    <div id="buttonsHolder"></div>
    <div id="name"></div>

    0 讨论(0)
  • 2021-01-28 08:27

    Try this:

    var html = '';
    var c;
    for (var i = 65; 90 >= i; i++) {// A-65, Z-90
      c = String.fromCharCode(i);
      html += '<button onclick="setLetter(\'' + c + '\');">' + c + '</button>';
    }
    document.getElementById('box').innerHTML = html;
    
    var setLetter = function(x) {
      document.getElementById('name').innerHTML += x;
    };
    <div id="box"></div>
    <div id="name"></div>

    0 讨论(0)
提交回复
热议问题