简体   繁体   中英

.click() doesn't work on page load but works in console

Here is my code:

<script>
  document.getElementById("test").click();
</script>

Is there a reason why it doesn't trigger the click(); on page load but when I do it in the console for on Firefox, it works. Why is that and how do i fix it?

EDIT: I have also tried this:

<script>
  $(document).ready(function() {
    $('#test').trigger('click');
 });
</script>

still doesn't work...

Since you haven't post your whole page, I think the highest probability is that the "test" element is not loaded when the script is executed. If you want to ensure your scripts get's executed, you should use

$( document ).ready(function() {
    $("#test").click();
});

Working Example:

</!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        function printTest() {
            alert('test')
        }
    </script>
</head>
<body>
<script type="text/javascript">
    $( document ).ready(function() {
        $("#test").click();
    });
    // document.getElementById("test").click();
</script>
<button id="test" onclick="printTest()"> Click Me</button>
</body>
</html>

Without seeing the rest of your code, I need to guess here. Given that your code fails when in the document, yet functions as expected when entered into the console after the page has loaded, it's reasonably safe to assume the DOM hasn't finished loading yet.

To deal with this, we attach a function to the load event of the window object. Once the HTML/CSS/JS files have been loaded and parsed, the event is fired. We handle that event by locating and clicking the desired button.

 window.addEventListener('load', onDocLoaded, false); function onDocLoaded(evt) { document.getElementById('test').click(); } 
 <button id='test' onclick='alert("you clicked the test button");'>Click me</button> 

keep in mind to include the jquery library befor you do others. this jquery google CDN provide different version of jquery online cdn. use one of them and hope following helps to you.

refer this working demo. ....

 <html> <head></head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <style> #mybutton{ width: 100px; height: 50px; color: white; background-color: orange; border: 0; border-radius: 5px; font-family: monospace; cursor: pointer; } </style> <body> <button id="mybutton">Click me to see th alert</button> <script type="text/javascript"> $("#mybutton").click(function(){ alert("jquery and click event is working fine. ..."); }); </script> </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