如何在按下按钮后灰显并禁用按钮一次?

时间:2015-12-07 14:34:42

标签: javascript html

嗨,我想在按下一次后灰显并禁用按钮(div中的每个按钮)。这样用户将无法再次按下它,直到他/她刷新页面。希望我的问题是正确的问题..我希望你能理解我。 这是我的HTML页面代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
     <head>
            <!--this name will be visible on the tab-->
           <title>Multiplayer</title>
           <!--this is to link HTML and CSS together-->
             <link rel="stylesheet" type="text/css" href="Hangman.css">
             <script> var currentPlayingWord = "<?php echo $result["word"] ?>" </script>
             <script src="jquery-1.11.3.js"></script>
             <script src="JSforMultiPlayer.js"></script>

     </head>
     <body style="background-color:#00FFFF">
          <!--this is the picture on the webpage-->
          <img id="hangman-image" src="hangmanImage.png" alt="Hangman" style="width:660px;height:618px;" align="right">
          <!--these are the buttons which use to input the words in-->
          <div id="all-the-buttons">
             <div id="first-row" class="row-button">
                   <button type="button">Q</button>
                   <button type="button">W</button>
                   <button type="button">E</button>
                   <button type="button">R</button>
                   <button type="button">T</button>
                   <button type="button">Y</button>
                   <button type="button">U</button>
                   <button type="button">I</button>
                   <button type="button">O</button>
                   <button type="button">P</button>
             </div>
             <div id="second-row" class="row-button" >
                   <button type="button">A</button>
                   <button type="button">S</button>
                   <button type="button">D</button>
                   <button type="button">F</button>
                   <button type="button">G</button>
                   <button type="button">H</button>
                   <button type="button">J</button>
                   <button type="button">K</button>
                   <button type="button">L</button>
            </div>
            <div id="third-row" class="row-button" style="padding-top: 4px;">
                   <button type="button">Z</button>
                   <button type="button">X</button>
                   <button type="button">C</button>
                   <button type="button">V</button>
                   <button type="button">B</button>
                   <button type="button">N</button>
                   <button type="button">M</button>
                   <button id="reset-button" type="button">RESET</button>
            </div>
              <p class="mylives" type="text"></p>
         </div>
          <form>
               <input type="text" id="word-outcome"/>
        </form>
         <form>
               <input type="text" id="wrong-guesses"/>
           </form>
         <form>
             <input type="text" class="hint" style="display:none;" value="Hint: word is computer related." readonly></input>
        </form>
         <TABLE BORDER="5"    WIDTH="20%"   CELLPADDING="5" CELLSPACING="2" id="Score-Board">
          <TR>
              <caption id="table-title">Score Board</caption>
              </TH>
          </TR>
          <TR ALIGN="CENTER">
              <TH colspan="2" id="player1"></TH>
              <TH colspan="2" id="player2"></TH>
          </TR>
          <TR ALIGN="CENTER">
              <TH colspan="2" id="player1Score"></TH>
              <TH colspan="2" id="player2Score"> </TH>
          </TR>
         </TABLE>
     </body>

这是我的JavaScript代码:

var wordbank = ['browser', 'binary', 'cache', 'cookie', 'CSS', 'HTML', 'javascript', 'gigabyte', 'google', 'download']
var underscores = "";
var guessCounter = 0;
var score = 1000;
var player1Name;
var player2Name;
$(document).ready(function () {

    getPlayerNames();
    underscores = wordloop(currentPlayingWord);
    wordOutCome(underscores);
    guessCounter = 10;

    $('#all-the-buttons button').click(function () {
        letterPress($(this));
    });


});

var wordloop = function (word) {
    var wordcount = 0
    var underscores = "";
    while (wordcount < word.length) {
        underscores = underscores + "_";
        wordcount++;
    }
    return underscores;
}

var randomNumber = function () {
    var random = Math.floor((Math.random() * 9) + 0);
    return random;
}

var wordOutCome = function (underscores) {
    var wordoutcome = document.getElementById('word-outcome');
    wordoutcome.value = underscores;
}

function letterPress(button) {
    var text = button.text();
    if ("RESET" === text) {
        resetButton();
    }
    else {
        var result = isLetterInWord(text, currentPlayingWord);
        if (result == true) {
            increaseScore();
            replaceDashesForLetter(text);
            var hasDashes = noMoreDashes();
            if (hasDashes == true) {
                navigateToWinnerPage();
            }

        }
        else {
            decreaseGuessCount();
            decreaseScore();
            noMoreGuesses();
            addIncorrectGuessToWrongGuesses(text);
            noMoreLives();
        }


        $('#word-outcome').val(underscores);

    }
}

function isLetterInWord(guess, word) {
    var uppercaseGuess = guess.toUpperCase();
    var uppercaseWord = word.toUpperCase();
    for (var i = 0; i < uppercaseWord.length; i++) {
        console.log(i);
        if (uppercaseWord[i] === uppercaseGuess) {
            return true;
        }
        //get letter from word
        //is letter from word the same as guess
        //if letter from word is the same as guess return true
        //return false if guess is not in the word
    }
    return false;
}

function replaceDashesForLetter(letter) {
    for (var i = 0; i < currentPlayingWord.length; i++) {
        console.log(currentPlayingWord);
        var playingLetter = currentPlayingWord[i];
        var upperCaseCurrentLetter = playingLetter.toUpperCase();
        if (upperCaseCurrentLetter == letter) {
            underscores = setCharAt(underscores, i, letter);
        }
    }
//for each letter in current word being played
//does letter guessed match the letter in the current word
//if letter guessed matches the letter in the current word - then replace the dash at the index (count in loop) with the letter guessed
//for each of the letters in the word being played there is a dash
//if the letter is at the index of a dash then replace that dash with the letter (which is the users guess)
}

function setCharAt(str, index, chr) {
    //get first part of word up to character we want to replace
    var first = str.substr(0, index);
    //get second part of word ONE letter AFTER character we want to replace
    var second = str.substr(index + 1);
    //result is the first part plus the character to replace plus the second part
    return first + chr + second;
}

var addIncorrectGuessToWrongGuesses = function (guess) {
    var currentText = document.getElementById("wrong-guesses").value;
    document.getElementById("wrong-guesses").value = currentText + guess;
    //As the guess is wrong
    //add the guess to the list of incorrect guesses displayed on the screen
}

var greyOutButton = function (button) {
    //grey out the button
    //make sure that the user cannot press the button anymore
}

function resetButton() {
    location.href = "HangmanHomePage.php";
    //Send user to the home page
}

var decreaseGuessCount = function () {
    guessCounter = guessCounter - 1;
    if (guessCounter === 3) {
        showHint();
    }
//guess count should be decreased by one
}

var noMoreGuesses = function () {
    if (guessCounter === 0) {
        location.href = "Looser Page.php";
    }
    //do something when no more guesses (navigate to loser page)
}

var noMoreDashes = function () {
    var i = underscores.indexOf("_");
    if (i > -1) {
        return false;
    }
    return true;
    //if index of '_' is not -1 then there are dashes
}

var navigateToWinnerPage = function () {
    location.href = "Winner Page.php?score="+score;
}

var noMoreLives = function () {
    var showLives = "You have " + guessCounter + " lives";
    var test = document.getElementsByClassName("mylives");
    test.textContent = showLives;
}

function showHint() {
    document.getElementsByClassName('hint').style.display = "block";
}
function increaseScore(){
    score = score + 100;
    console.log(score);
    var showScore = $("#player1Score");
    showScore.text(score);
}
function decreaseScore(){
    score = score - 100;
    console.log(score);
    var showScore = $("#player1Score");
    showScore.text(score);
}

function navigateToDifficultyForMultiPlayer() {
    //set player names in session
    setPlayerNames();
    //navigate to DifficultyForMultiPlayer page
    location.href = "DifficultyForMultiPlayer.html";
}

function setPlayerNames() {
    var firstPlayerName = document.getElementById("playerOneName").value;
    var secondPlayerName = document.getElementById("playerTwoName").value;
    console.log(firstPlayerName + " " + secondPlayerName);
    sessionStorage.setItem("Player1Name", firstPlayerName);
    sessionStorage.setItem("Player2Name", secondPlayerName);
}
function getPlayerNames(){
    player1Name = sessionStorage.getItem("Player1Name");
    player2Name = sessionStorage.getItem("Player2Name");
    console.log(player1Name + " " + player2Name);
    document.getElementById("player1").innerHTML = player1Name;
    document.getElementById("player2").innerHTML = player2Name;
}
function displayScore () {
    var playerOneScore = score;

}

5 个答案:

答案 0 :(得分:4)

我最近需要这样做。但我所做的是,禁用按钮只有几秒钟,这样它足够长,以防止双击,并且足够短,如果有任何验证错误等仍然继续。

<script type="text/javascript">

        $(document).on('click', ':button', function (e) {

            var btn = $(e.target);
            btn.attr("disabled", "disabled"); // disable button

            window.setTimeout(function () {
                btn.removeAttr("disabled"); // enable button
            }, 2000 /* 2 sec */);
        });

</script>

如果您希望按钮保持禁用状态,请使用此

<script type="text/javascript">

        $(document).on('click', ':button', function (e) {

            var btn = $(e.target);
            btn.attr("disabled", "disabled"); // disable button

        });

</script>

答案 1 :(得分:1)

在点击功能中,您可以执行以下操作:

$("button").click(function() {
var buttonId = this.id;
document.getElementById("buttonId").disabled = true; //OR
document.getElementById("buttonId").readOnly= true;
});

答案 2 :(得分:0)

你应该重新考虑一些逻辑。

尝试这样的事情(没有测试过)

<强>的JavaScript

$scope.letters = "qwertyuiopasdfghjklzxcvbnm";
$scope.lettersArray = [];
for (var i=0 ; i<$scope.letters.length ; i++) {
    $scope.lettersArray.push($scope.letters[i];
}

$scope.disableMe = function(event) {
    $(event.currentTarget).css('disabled', 'true');
}

<强> HTML

<div ng-repeat="letter in lettersArray">
    <button type="button" ng-click="disableMe($event)">{{letter}}</button>
</div>

答案 3 :(得分:0)

您可以使用disabled属性:

$('#all-the-buttons button').click(function (e) {
    if ($(this).is(':disabled')) e.preventDefault();
    else letterPress($(this));
});

var greyOutButton = function (button) {
   button.prop('disabled', true);
}

使用CSS定位它以更改样式:

button:disabled {
    background: #F5F5F5;
    color : #C3C3C3;
}

答案 4 :(得分:0)

只需使用jQuery添加一个属性(如果你愿意,可以为游标添加css)

$(document).ready(function () {
        $("button").attr("disabled", "disabled").css("cursor", "not-allowed");
    });

或简单的javascript:

  document.getElementsByTagName("button")[0].setAttribute("disabled", "disabled");