Как напечатать результат функции JavaScript в HTML - PullRequest
0 голосов
/ 02 марта 2019

У меня есть функция, в которой я хочу напечатать строку в html из функции в javascript, которая использует заглавные буквы в каждой строке.

JavaScript:

function crazyCaps(s){
    let result =""
    for (let i = 0; i < s.length; i++)
        if (i%2 == 0){
            result += s[i].toLowerCase();
            else {
                result += s[i].toUpperCase();
            }
        }
        console.log(result);
    }
    crazyCaps("helloworld");
    window.onload = crazyCaps();

HTML:

<!DOCTYPE html>
<html>
<head>
<script src ="crazycaps.js" type="text/javascript"></script>
</head>

    <body>
    crazyCaps();

    </body>
</html>

Ответы [ 7 ]

0 голосов
/ 02 марта 2019

// INSIDE crazycaps.js

function crazyCaps(s){
    let result = "";
    for (let i = 0; i < s.length; i++){
      if (i%2 == 0){
         result += s[i].toLowerCase();
      } else {
         result += s[i].toUpperCase();
      }
    }
    return result;
    // the string is returned as a result
 }

console.log(crazyCaps("helloworld"));
// the console.log now occurs OUTSIDE of the crazyCaps function
    
window.onload = () => 
        document.body.textContent = crazyCaps( "example crazy capitals");
// window.onload is assigned to a CALL BACK FUNCTION, which is executed onload
<!DOCTYPE html>
<html>
<head>
<script src="crazycaps.js" type="text/javascript"></script>
</head>
    <body>
    </body>
</html>
0 голосов
/ 02 марта 2019

Вы можете достичь этого следующим образом:

function crazyCaps(s) {
  let result = ""
  for (let i = 0; i < s.length; i++) {
    if (i % 2 == 0) {
      result += s[i].toLowerCase();
    } else {
      result += s[i].toUpperCase();
    }
  }
  //Make sure to return your result instead of just logging it
  return result;
}

document.addEventListener('DOMContentLoaded', function() {
  this.body.textContent = crazyCaps('helloworld')
});
<html>

<head>
</head>

<body>
</body>

</html>
0 голосов
/ 02 марта 2019

Не проверено, но должно работать:

JS:

function crazyCaps(s){
    let result =""
    for (let i = 0; i < s.length; i++) {
        if (i%2 == 0){
            result += s[i].toLowerCase();
        } else {
            result += s[i].toUpperCase();
        }
    }
    document.getElementById("text").innerText=result;
}
window.onload = crazyCaps('helloworld');

HTML

    <!DOCTYPE html>
    <html>
    <head>
    <script src ="crazycaps.js" type="text/javascript"></script>
    </head>
        <body>
          <div id="text"></div>
        </body>
    </html>
0 голосов
/ 02 марта 2019

Современный подход состоит в том, чтобы установить пустой HTML-элемент в качестве заполнителя для ввода результатов, а затем заполнить его при необходимости.Кроме того, вам действительно не нужен обработчик событий window.onload, просто переместите <script> непосредственно перед тем, как элемент body закроется.К этому моменту весь HTML-код был проанализирован в DOM и готов к взаимодействию с ним.

<!DOCTYPE html>
<html>
  <head>

  </head>
  <body>
    <!-- JavaScript will access this element and populate it.-->
    <div id="results"></div>
    
    
    <!-- Placing the script just before the closing body tag ensures
         that by the time the parser reaches this point, all the HTML
         will have been read into memory. -->
    <script src ="crazycaps.js" type="text/javascript"></script>
           
    <script>
      // Get a reference to the element where the output will go
      let output = document.getElementById("results");
      
      function crazyCaps(s){
        let result ="";
        for (let i = 0; i < s.length; i++){
          if (i%2 == 0){
            result += s[i].toLowerCase();
          } else {
            result += s[i].toUpperCase();
          }
        }
        output.textContent = result;  // Populate the element
      }
      crazyCaps("helloworld");  
    </script>
  </body>
</html>
0 голосов
/ 02 марта 2019
function weird_string_format(string){
  let temp = "";
  for(let i = 0; i < string.length; i++){
    temp += (i % 2 === 0) ? string[i] : string.charAt(i).toUpperCase() 
  }
  return temp;
}

document.write(temp);
0 голосов
/ 02 марта 2019

В вашем коде есть небольшие ошибки, вы не можете вызывать функции javascript между вашими html-тегами.написание crazyCaps ();просто выводит "crazyCaps ();"в текстовом виде.Вам нужно вернуть созданную вами строку, а затем присвоить этот результат элементу в вашем html, что можно сделать с помощью document.getElementById('IDGOESHERE').textContent.Ваше предложение if else необходимо структурировать так, чтобы концы curlybracers заканчивались, и начиналось ваше утверждение else, if (){} else{} вы поместили свое выражение else внутри вашего оператора if.

function crazyCaps(s) {
  let result = ""
  for (let i = 0; i < s.length; i++)
    if (i % 2 == 0) {
      result += s[i].toLowerCase();
    } else {
      result += s[i].toUpperCase();
    }
  console.log(result);
  return result;
}
document.getElementById('crazyoutput').textContent = crazyCaps("helloworld");
<body>
  <div id="crazyoutput">
  </div>
</body>

https://jsfiddle.net/zeonfrost/4q01x68z/1/

0 голосов
/ 02 марта 2019

Используйте document.body.textContent += result, чтобы записать результат на страницу.И вам не нужно иметь оператор window.onload, вам просто нужна функция:

 

function crazyCaps(s) {
    let result =""
    for (let i = 0; i < s.length; i++) {
        if (i%2 == 0) {
            result += s[i].toLowerCase();
        } else {
            result += s[i].toUpperCase();
        }
    }
    document.body.textContent += result;
}
crazyCaps("helloworld");
 

<body></body>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...