简体   繁体   中英

Javascript DOM manipulation: changing text of an element

I tried to print the results of the function calculation() to the text area but it seems not working. Can you please help!

<head>
  <title>Lab 6</title>
<script>
function calculate(){
for (var i=100; i<1000; i++) {
var x = i%10;
var y = Math.floor((i/10)%10);
var z = Math.floor((i/100)%10);
 if (i== x*x*x +y*y*y + z*z*z) {

document.getElementbyTagname("textarea").innerHtml = i;
document.getElementbyTagname("button").addEventListener("click",
calculate());
}}} 

</script>
</head>

<body>
<textarea rows="4" cols="50"> </textarea>
<button type="button">Click Me!</button>
</body>

</html>

Hi I have edit your code to make it work, I don't really get your logic, so not sure if that is what you want. But you can look at the my syntax to refine your own code. Also You made several mistakes. 1. 'getElementbyTagname' should be 'getElementsByTagName' 2. you didn't put the event function to the right place to trigger the click event.

`var btn = document.querySelector(' .btn') btn.addEventListener('click', function(e){ calculate()

})
function calculate(){
      for (var i=100; i<1000; i++) {
                var x = i%10;
                var y = Math.floor((i/10)%10);
                var z = Math.floor((i/100)%10);
                if (i== x*x*x +y*y*y + z*z*z) {
                    var text = document.querySelector(' .demo')
                   text.innerHTML = i

                }}}`

I try to rewrite your code. try once may this help...

<head>
  <title>Lab 6</title>
<script>
function calculate()
{
    for (var i=100; i<1000; i++) 
    {
        var x = i%10;
        var y = Math.floor((i/10)%10);
        var z = Math.floor((i/100)%10);
        if (i== x*x*x +y*y*y + z*z*z) 
        {

            document.getElementsByTagName("textarea")[0].innerHtml = i;

        }
    }
} 
document.getElementsByTagName("button")[0].addEventListener("click",calculate());
</script>
</head>

<body>
<textarea rows="4" cols="50"> </textarea>
<button type="button">Click Me!</button>
</body>

Try this out. Made many changes to your code,

 function calculate(){ var txt=""; for (var i=100; i<1000; i++) { var x = i%10; var y = Math.floor((i/10)%10); var z = Math.floor((i/100)%10); if (i== x*x*x +y*y*y + z*z*z) { txt = txt + i + "\\n"; } } document.getElementById("textarea").innerHTML = txt; } 
 <html> <head> <title>Lab 6</title> </head> <body> <textarea rows="4" cols="50" id="textarea"> </textarea> <button type="button" onclick="calculate();">Click Me!</button> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM