Onclick() function on working

后端 未结 4 1069
名媛妹妹
名媛妹妹 2020-12-22 13:40

all! I am having a problem using the a simple onclick method. Kindly please help me out. Here is that code... When i click on the button nothing really happens.



        
相关标签:
4条回答
  • Try this: http://jsfiddle.net/uxfD4/

    the onclick assignment accepts a function. What your code did was evaluate alert('hi'), returning null.

    0 讨论(0)
  • 2020-12-22 14:00
    window.onload=initall();
    

    calls the function initall and assigns the return value of initall as event handler. That is, initall is executed immediately and not when the load event is triggered.
    Similar for btn.onclick=alert('hi');. But in both cases, the return value is not a function.

    You have to assign functions to those properties, which are then being called when the event occurs.

    function initall(){
        var btn = document.getElementById('btn');
    
        btn.onclick = function() { // creates and assigns the function at once
            alert('hi');
        };
    }
    
    window.onload = initall; // assign the function reference, no `()`.
    

    I recommend to read the excellent tutorials at quirksmode.org to learn about event handling and of course the MDN JavaScript Guide for the JavaScript basics.

    0 讨论(0)
  • 2020-12-22 14:14

    Onclick should be a function, not a statement. Try

    btn.onclick=function(){ 
      alert('hi');
    }
    
    0 讨论(0)
  • 2020-12-22 14:16
    Try this for onclick javascript function call   
    
    
        function initall(){
    
            var btn=document.getElementById('btn');
    
            btn.onclick=alert('hi');
        }
        <!DOCTYPE HTML>
        <html>
        <head>
        <meta charset="utf-8">
    
        <title>Untitled Document</title>
    
        <script type="text/javascript" src="testjs.js"></script>
        </head>
    
        <body>
        <input type="text" required name="id">
        <input type="button"  id="btn" value="send" onclick="javascript:initall();">
        <div id="result"></div>
        </body>
    
        </html>
    
    0 讨论(0)
提交回复
热议问题