无法更改函数内的id值

时间:2014-03-07 19:16:59

标签: javascript jquery

我想在“on”函数中更改<h2>及其id的值,但不会更改。

这是代码:                                        

<div id="boardGame">
</div>

<script type="text/javascript">

    json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}

    var score = 0
    var nb = 0
    var iter = 0
    var song
    var start
    var click
    var listSongs = []

    getHome()

    $(document).on("click", '.calc_btn', function() {

        iter++
        $("#valueIter").html(iter+"/10")
        if(iter == 10)
        {
            gameOver(score)
        }
        else 
        {
            click = new Date()
            time = (click.getTime() - start.getTime())/1000
            if($(this).val() == song){
                if(time <= 15)
                    score += parseInt((-1000/14)*time+929)
                $("#valueScore").html(score)
                $("#valueScore").css( "color", "green" )
            } 
            else
            {
                $("#valueScore").html(score)
                $("#valueScore").css( "color", "red" )
            }
            nb += 1
            getSong()
        }
    })

    function getHome()
    {
        score = 0
        iter = 0
        listSongs = []
        $("#boardGame").html("<h2>Welcome to The Game of Monkeys</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' class='stres' value='Start' onclick='getSong()'></td></tr></tbody></table")
    }

    function getSong()
    {
        var keys = [];
        for (var prop in json_dic) {
            if (json_dic.hasOwnProperty(prop)) {
                keys.push(prop);
            }
        }

        song = keys[ keys.length * Math.random() << 0 ];
        listSongs = [ song ]
        url = json_dic[song]

        while(listSongs.length <= 4)
        {
            var keys = [];
            for (var prop in json_dic) {
                if (json_dic.hasOwnProperty(prop)) {
                    keys.push(prop);
                }
            }

            song_random = keys[ keys.length * Math.random() << 0 ];
            listSongs.push(song_random)
        }

        $("#boardGame").html('<table class="calculatrice" id="calc"> '+
            '<tbody>' +
            '<tr>' +
            '<td class="calc_td_btn">' +
            '<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
            '<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
            '</div>' +
            '</div>' +
            '</td>' +
            '</tr>');

        for(var i = 0; i <= 4; i++)
        {
            var randomIndex = Math.floor(Math.random() * listSongs.length);
            var randomString = listSongs[randomIndex];
            $("#boardGame").append('<tr>'+
                '<td class="calc_td_btn">' +
                '<input type="button" class="calc_btn" value="'+randomString+'">' +
                '</td>' +
                '</tr>')
            var index = listSongs.indexOf(randomString);
            listSongs.splice(index, 1);
        }

        $("#boardGame").append('<tr>' +
            '<td class="calc_td_btn">' +
            '<h2 id="valueScore">0 points</h2>' +
            '<h2 id="valueIter">0/10</h2>' +
            '<input type="button" class="stres" onclick="getHome()" value="Restart">' +
            '</td>' +
            '</tr>' +
            '</tbody>' +
            '</table>')

        var nb = getRandomInt(0,100)
        $("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")

        start = new Date()

    }

    function getRandomInt (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function gameOver(score){
        $("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
    }

</script>




</body>
</html>

#valueScore的价值不想改变。我认为这是一个范围问题,但我无法绕过它。

我可以在控制台中使用#valueScore的值,或者如果我将代码段$("#valueScore").html(score)放在我的JavaScript中的其他位置。

编辑:添加了整个代码

2 个答案:

答案 0 :(得分:0)

问题是你在第93-106行吹走了所有元素的DOM而你正在重新创建它们。因此,您正在设置分数的元素将被销毁并替换为完全不同的<h2>

不是破坏所有内容(第82行是替换'#boardGame'的html),你需要使用JQuery来修改已经存在的按钮,以便为它们提供歌曲列表的名称

作为替代方案,请尝试这样做:

  1. 为所有多项选择按钮添加一个类:'。choice_button'
  2. 在所有按钮周围放置<div id="button_wrapper">,以便您可以插入新按钮。
  3. 而不是替换'#boardGame'的HTML,只需销毁所有按钮:$('#button_wrapper .choice_button').remove()
  4. 现在您可以使用for循环插入新按钮,就像您在第93行上所做的那样
  5. 现在$('#valueScore')还没有被吹走,因此得分应保持不变。
  6. 我修改了你的代码,以便将它带到我认为的地方,这就是你所追求的:

    <div id="boardGame">
    </div>
    
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript">
    
        json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}
    
        var score = 0
        var nb = 0
        var iter = 0
        var song
        var start
        var click
        var listSongs = []
    
        getHome()
    
        $(document).on("click", '.calc_btn', function() {
    
            iter++
            $("#valueIter").html(iter+"/10")
            if(iter == 10)
            {
                gameOver(score)
            }
            else 
            {
                click = new Date()
                time = (click.getTime() - start.getTime())/1000
                if($(this).val() == song){
                    if(time <= 15)
                        score += parseInt((-1000/14)*time+929)
                    $("#valueScore").html(score)
                    $("#valueScore").css( "color", "green" )
                } 
                else
                {
                    $("#valueScore").html(score)
                    $("#valueScore").css( "color", "red" )
                }
                nb += 1
                getSong()
                return false;
            }
        })
    
        function getHome()
        {
            score = 0
            iter = 0
            listSongs = []
            $("#boardGame").html(
                '<h2>Welcome to The Game of Monkeys</h2>'+
                '<table class="calculatrice" id="calc">' +
                    '<tbody>' +
                    '</tbody>' +
                '</table>' +
                '<div id="gameButtons" style="display: none;">' +
                    '<h2 id="valueScore">0 points</h2>' +
                    '<h2 id="valueIter">0/10</h2>' +
                    '<input type="button" class="stres" onclick="getHome()" value="Restart">' +
                '</div>' +
                '<input type="button" class="stres" value="Start" onclick="getSong()">'
            )
        }
    
        function getSong()
        {
            var keys = [];
            for (var prop in json_dic) {
                if (json_dic.hasOwnProperty(prop)) {
                    keys.push(prop);
                }
            }
    
            song = keys[ keys.length * Math.random() << 0 ];
            listSongs = [ song ]
            url = json_dic[song]
    
            while(listSongs.length <= 4)
            {
                var keys = [];
                for (var prop in json_dic) {
                    if (json_dic.hasOwnProperty(prop)) {
                        keys.push(prop);
                    }
                }
    
                song_random = keys[ keys.length * Math.random() << 0 ];
                listSongs.push(song_random)
            }
    
            // adds the music player, of course
            $('#calc tbody').html (
                '<tr>' +
                '<td class="calc_td_btn">' +
                '<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
                '<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
                '</div>' +
                '</div>' +
                '</td>' +
                '</tr>');
    
            // adds the multiple choice buttons
            for(var i = 0; i <= 4; i++)
            {
                var randomIndex = Math.floor(Math.random() * listSongs.length);
                var randomString = listSongs[randomIndex];
                $("#calc tbody").append('<tr>'+
                    '<td class="calc_td_btn">' +
                    '<input type="button" class="calc_btn" value="'+randomString+'">' +
                    '</td>' +
                    '</tr>')
                var index = listSongs.indexOf(randomString);
                listSongs.splice(index, 1);
            }
    
            // shows the score and the restart button
            $('#gameButtons').show();
    
            var nb = getRandomInt(0,100)
            $("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")
    
            start = new Date()
    
        }
    
        function getRandomInt (min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
    
        function gameOver(score){
            $("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
        }
    
    </script>
    </body>
    </html>
    

答案 1 :(得分:-2)

哦,我觉得我看到了问题。您不需要使用.html函数。

使用jQuery:

$("#valueIter").val(iter+"/10");
$("#valueScore").val(score);

html函数用于使用原始html填充元素。这里的不同之处在于jQuery提供.val()和.text()作为任何元素的getter和setter,等同于javascript equivelent

element.value = score;