如何在不立即执行“点击”功能的情况下在我的文本区域中具有“必需”?

我试着把我的文本区域放进去。但它不起作用,因为我的函数立即执行。我怎样才能要求先填写我的文本区域,而不立即执行点击?这是我的代码:requiredonclick="displayText()"


网页:


<!DOCTYPE html>

<html>

  <head>

    <title>Word Counter</title>

  </head>

  <body>

    <div id="input-page">

      <h1>Word Counter</h1>

      <form action="">

        <textarea id="inputted-text" type="text" rows="22" cols="60"></textarea>

        <br />

      </form>

      <button onclick="displayText()">COUNT</button>

    </div>


    <div id="count-page" style="display: none;">

      <h1>Your Text:</h1>

      <p id=display-user-text></p>

      <div>

         <h1 id="word-count">Count: </h1>

      </div>

    </div>

  </body>

  <script src="app.js"></script>

</html>

脚本:


const displayText = () => {

  const inputPage = document.getElementById("input-page");

  const countPage = document.getElementById("count-page");

  inputPage.style.display = "none";

  // get user's inputted text

  const inputtedText = document.getElementById("inputted-text");

  const inputtedTextValue = inputtedText.value;

  // diplay user's inputted text

  document.getElementById("display-user-text").innerText = inputtedTextValue;

  countPage.style.display = "block";

  console.log(countWords(inputtedTextValue));

};


const countWords = (str) => {

  return str.split(" ").length;

};


const renderWordCount = () => {

  document.getElementById("word-count") = wordCount;

};

奖励:除了标题之外,我还可以显示我的单词计数,而不仅仅是在我的控制台上显示它?Count:


慕少森
浏览 86回答 1
1回答

眼眸繁星

您希望系统在文本区域为空时发出警告。您可以通过将 If-else 条件表达式添加到代码中来执行此操作。const displayText = () => {&nbsp; const inputPage = document.getElementById("input-page");&nbsp; const countPage = document.getElementById("count-page");&nbsp; const inputtedText = document.getElementById("inputted-text");&nbsp; const inputtedTextValue = inputtedText.value;&nbsp; if (inputtedText.value !== "") { // normal flow will continue if the text-area is not empty&nbsp; &nbsp; inputPage.style.display = "none";&nbsp; &nbsp; document.getElementById("display-user-text").innerText = inputtedTextValue;&nbsp; &nbsp; countPage.style.display = "block";&nbsp; } else { // if the text-area is empty, it will issue a warning.&nbsp; &nbsp; alert("this area required")&nbsp; }&nbsp; console.log(countWords(inputtedTextValue));};const countWords = (str) => {&nbsp; return str.split(" ").length;};const renderWordCount = () => {&nbsp; document.getElementById("word-count") = wordCount;};<div id="input-page">&nbsp; <h1>Word Counter</h1>&nbsp; <form action="">&nbsp; &nbsp; <textarea id="inputted-text" type="text" rows="22" cols="60"></textarea>&nbsp; &nbsp; <br />&nbsp; </form>&nbsp; <button onclick="displayText()">COUNT</button></div><div id="count-page" style="display: none;">&nbsp; <h1>Your Text:</h1>&nbsp; <p id="display-user-text"></p>&nbsp; <div>&nbsp; &nbsp; <h1 id="word-count">Count: </h1>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript