Я думаю, что у меня проблема с обработчиками событий, которые не запускают функции при первом щелчке. с двумя щелчками мыши на работу. затем после нажатия на дополнительные кнопки это похоже на то, что они нажимают на всем протяжении процесса

Я новичок в кодировании HTML js вместе и использую этот сайт для решения всех своих проблем. но я не могу найти здесь ничего, что помогло бы мне. извините, если я получил ответ на то, что мне нужно сделать, и просто не смог найти нужный пост. извините, если я убью правильный способ публикации

Я попытался ввести код в head и body в разных комбинациях, чтобы посмотреть, не меняются ли результаты, ничего не работает

<html>

<head>
  <title>resource farming</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial- 
        scale=1.0">
</head>

<body>
  <p>
    <button id="mine" onclick="mine()">mine</button>
    <input type="text" id="credit" value="10000"></input>
    click mine to gain credit delay to mine is 5seconds
  </p>
  <p>
    <button id="btncoal" onclick="buycoal()">buy coal</button>
    <input type="text" id="coal" value="1000"> </input>
    click buy to gain coal cost (10 credit) delayed 7.5seconds
  </p>
  <p>
    <button id="btnironore" onclick="buyironore()">buy iron ore</button>
    <input type="text" id="ironore" value="1000"></input>
    click buy to gain iron ore (cost 10 credit) delayed 7.5seconds
  </p>
  <p>
    <button id="btnironbar" onclick="buyironbar()">Buy Iron Bar</button>
    <input type="text" id="ironbar" value="1000"></input>
    click buy to gain iron bar (cost 1 coal 1 iron ore)delayed 10seconds
  </p>
  <p>
    <button id="btnsteelbar" onclick="buysteelbar()">buy steel bar</button>
    <input type="text" id="steelbar" value="0"></input>
    click to gain steel bar (cost 5coal 2iron bars) delayed 20 seconds
  </p>
  <script type="text/javascript" language="javascript">
    var credit1 = 10000;
    var coal1 = 1000;
    var ironore1 = 1000;
    var ironbar1 = 1000;
    var steelbar1 = 0;
    var sleep = 0;


    function mine() {

      document.getElementById('mine').disabled = true;
      document.getElementById('credit').value = credit1;
      credit1 = credit1 + 10;
      sleep = setTimeout(enablemine, 5000);
    }

    function enablemine() {
      document.getElementById('mine').disabled = false;
    }


    function buycoal() {

      if (document.getElementById('credit').value > 10) {
        document.getElementById('btncoal').disabled = true;
        document.getElementById('credit').value = credit1;
        credit1 = credit1 - 10;
        document.getElementById('coal').value = coal1;
        coal1 = coal1 + 1;
        sleep = setTimeout(enablebtncoal, 7500);
      } else {
        document.getElementById('credit').value = credit1;

        document.getElementById('coal').value = coal1;

      }

    }

    function enablebtncoal() {
      document.getElementById('btncoal').disabled = false;
    }


    function buyironore() {

      if (document.getElementById('credit').value > 10) {
        document.getElementById('credit').value = credit1;
        credit1 = credit1 - 10;
        document.getElementById('ironore').value = ironore1;
        ironore1 = ironore1 + 1;
        document.getElementById('btnironore').disabled = true;
        sleep = setTimeout(enablebtnironore, 7500);
      } else {
        document.getElementById('credit').value = credit1;

        document.getElementById('ironore').value = ironore1;

      }
    }

    function enablebtnironore() {
      document.getElementById('btnironore').disabled = false;
    }

    function buyironbar() {
      if (document.getElementById('coal').value > 1) {
        if (document.getElementById('ironore').value > 1) {
          document.getElementById('coal').value = coal1;
          coal1 = coal1 - 1;
          document.getElementById('ironore').value = ironore1;
          ironore1 = ironore1 - 1;
          document.getElementById('ironbar').value = ironbar1;
          ironbar1 = ironbar1 + 1;
          document.getElementById('btnironbar').disabled = true;
          sleep = setTimeout(enableironbar, 10000);
        }
      } else {
        document.getElementById('coal').value = coal1;

        document.getElementById('ironore').value = ironore1;

        document.getElementById('ironbar').value = ironbar1;

      }
    }

    function enableironbar() {
      document.getElementById('btnironbar').disabled = false;
    }

    function buysteelbar() {
      if (document.getElementById('coal').value > 5) {
        if (document.getElementById('ironbar').value > 2) {
          document.getElementById('coal').value = coal1;
          coal1 = coal1 - 5;
          document.getElementById('ironbar').value = ironbar1;
          ironbar1 = ironbar1 - 2;
          document.getElementById('steelbar').value = steelbar1;
          steelbar1 = steelbar1 + 1;
          document.getElementById('btnsteelbar').disabled = true;
          sleep = setTimeout(enablesteelbar, 20000);
        }
      } else {
        document.getElementById('coal').value = coal1;
        document.getElementById('ironbar').value = ironbar1;
        document.getElementById('steelbar').value = steelbar1;
      }
    }

    function enablesteelbar() {
      document.getElementById('btnsteelbar').disabled = false;
    }
  </script>




</body>

</html>

Желательно: каждый щелчок запускает функции, применяет значения в полях, добавляя вычитание в соответствии с настроенными функциями

Чтобы получить реальные результаты, нужно два щелчка мышки. также кажется, что щелчок позади влияет на то, как больше результатов щелчок, чем должен быть

0
demonica 22 Окт 2019 в 08:58
Отслеживайте свой клик, добавляя console.log или alert() во все функции кликов и проверяя при первом клике, вызывается эта функция или нет.
 – 
Vibha Chosla
22 Окт 2019 в 09:06
Похоже, проблема в вашем коде, потому что все клики работают при первом клике. Пожалуйста, проверьте ссылку ниже. jsfiddle.net/td6zo95u
 – 
Vishal modi
22 Окт 2019 в 09:09
Регистрирует первый щелчок в console.log, но функции не работают до второго щелчка
 – 
demonica
22 Окт 2019 в 09:18

1 ответ

Лучший ответ

Нет проблем с щелчком. В вашем коде есть логическая ошибка. Возьмем кнопку щелчка «шахта». Начальное значение - «10000», которое вы задаете в html. Когда вы нажимаете на «шахту», сначала устанавливается входное значение «10000», так как вы инициализируете значение credit1 = 10000. И устанавливая значение ввода, а затем добавляете 10 к исходному значению. Таким образом, при первом нажатии значение будет 10000. Теперь значение кредита1 = 10000 + 10.

При втором щелчке значение кредита1 = 10000 + 10, как вы добавили 10 при предыдущем щелчке.

Прочтите комментарий в функции ниже.

function mine() {
document.getElementById('mine').disabled = true;
document.getElementById('credit').value = credit1;  // On first click setting the value to 10000 which is the same as previos value
credit1 = credit1 + 10; // Now you are adding 10. This will not reflect in input box. And will show when you click second time.
sleep = setTimeout(enablemine, 5000);

}

<html>

<head>
    <title>resource farming</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial- 
     scale=1.0">
</head>

<body>
    <p>
        <button id="mine" onclick="mine()">mine</button>
        <input type="text" id="credit" value="10000"></input>
        click mine to gain credit delay to mine is 5seconds
    </p>
    <p>
        <button id="btncoal" onclick="buycoal()">buy coal</button>
        <input type="text" id="coal" value="1000"> </input>
        click buy to gain coal cost (10 credit) delayed 7.5seconds
    </p>
    <p>
        <button id="btnironore" onclick="buyironore()">buy iron ore</button>
        <input type="text" id="ironore" value="1000"></input>
        click buy to gain iron ore (cost 10 credit) delayed 7.5seconds
    </p>
    <p>
        <button id="btnironbar" onclick="buyironbar()">Buy Iron Bar</button>
        <input type="text" id="ironbar" value="1000"></input>
        click buy to gain iron bar (cost 1 coal 1 iron ore)delayed 10seconds
    </p>
    <p>
        <button id="btnsteelbar" onclick="buysteelbar()">buy steel bar</button>
        <input type="text" id="steelbar" value="0"></input>
        click to gain steel bar (cost 5coal 2iron bars) delayed 20 seconds
    </p>
    <script type="text/javascript" language="javascript">
        var credit1 = 10000;
        var coal1 = 1000;
        var ironore1 = 1000;
        var ironbar1 = 1000;
        var steelbar1 = 0;
        var sleep = 0;

        function mine() {
            document.getElementById('mine').disabled = true;
            credit1 = credit1 + 10;
            document.getElementById('credit').value = credit1;
            sleep = setTimeout(enablemine, 5000);
        }

        function enablemine() {
            document.getElementById('mine').disabled = false;
        }

        function buycoal() {
            if (document.getElementById('credit').value > 10) {
                document.getElementById('btncoal').disabled = true;
                credit1 = credit1 - 10;
                document.getElementById('credit').value = credit1;
                coal1 = coal1 + 1;
                document.getElementById('coal').value = coal1;
                sleep = setTimeout(enablebtncoal, 7500);
            } else {
                document.getElementById('credit').value = credit1;
                document.getElementById('coal').value = coal1;
            }
        }

        function enablebtncoal() {
            document.getElementById('btncoal').disabled = false;
        }

        function buyironore() {
            if (document.getElementById('credit').value > 10) {
                document.getElementById('credit').value = credit1;
                credit1 = credit1 - 10;
                ironore1 = ironore1 + 1;
                document.getElementById('ironore').value = ironore1;
                document.getElementById('btnironore').disabled = true;
                sleep = setTimeout(enablebtnironore, 7500);
            } else {
                document.getElementById('credit').value = credit1;
                document.getElementById('ironore').value = ironore1;
            }
        }

        function enablebtnironore() {
            document.getElementById('btnironore').disabled = false;
        }

        function buyironbar() {
            if (document.getElementById('coal').value > 1) {
                if (document.getElementById('ironore').value > 1) {
                    coal1 = coal1 - 1;
                    ironbar1 = ironbar1 + 1;
                    ironore1 = ironore1 - 1;
                    document.getElementById('coal').value = coal1;
                    document.getElementById('ironore').value = ironore1;
                    document.getElementById('ironbar').value = ironbar1;
                    document.getElementById('btnironbar').disabled = true;
                    sleep = setTimeout(enableironbar, 10000);
                }
            } else {
                document.getElementById('coal').value = coal1;
                document.getElementById('ironore').value = ironore1;
                document.getElementById('ironbar').value = ironbar1;
            }
        }

        function enableironbar() {
            document.getElementById('btnironbar').disabled = false;
        }

        function buysteelbar() {
            if (document.getElementById('coal').value > 5) {
                if (document.getElementById('ironbar').value > 2) {
                    document.getElementById('coal').value = coal1;
                    coal1 = coal1 - 5;
                    steelbar1 = steelbar1 + 1;
                    ironbar1 = ironbar1 - 2;
                    document.getElementById('ironbar').value = ironbar1;
                    document.getElementById('steelbar').value = steelbar1;
                    document.getElementById('btnsteelbar').disabled = true;
                    sleep = setTimeout(enablesteelbar, 20000);
                }
            } else {
                document.getElementById('coal').value = coal1;
                document.getElementById('ironbar').value = ironbar1;
                document.getElementById('steelbar').value = steelbar1;
            }
        }

        function enablesteelbar() {
            document.getElementById('btnsteelbar').disabled = false;
        }
    </script>


</body>

</html>

Надеюсь, это поможет вам решить эту проблему.

0
Sohail Ashraf 22 Окт 2019 в 09:26
Вау, простое расположение линий портило мне все дело. спасибо, я знал, что это просто.
 – 
demonica
22 Окт 2019 в 09:40