سؤال

I am new to JS and trying to learn event handlers. i've been looking at this for hours and I think it is way simpler than I am finding it. Does anyone know why nothing happens when I click the button?

<script>
    function buttonClick(){
        document.getElementById("testButton").onclick = document.write("The button has been clicked!!!");
    }
    window.onload=buttonClick;
</script>

<input type="button" id="testButton" value="click me" />

هل كانت مفيدة؟

المحلول

It's because you need a function to assign onclick to, so this would work

 document.getElementById("testButton").onclick = function(){document.write("The button has been clicked!!!");}

that's an anonymous function.

نصائح أخرى

Your script is loading the buttonClick event on the page load. you need to remove that line and add an onClick to your input. You could write it this way:

<script>
function buttonClick(){
    document.write("The button has been clicked!!!");
}
</script>

<input type="button" id="testButton" value="click me" onClick="buttonClick()" />
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top