简体   繁体   中英

Jquery click function not triggering a click

I have this simple HTML page:

<html>

<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">  </script>

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

</head>

<body>
<a id="test" href="http://google.com">http://google.com</a>
</body>

</html>

I want to trigger a click event on the element called test on loading the page. The actual code is actually more sophisticated than that but this very basic example is not working. I checked the console log and there are no notices there.

The .click() you are triggering is correct but you are missing a click event for '#test' as shown :

$('#test').click(function(){
  alert('here');
});

Now your complete jquery code is as shown :

<script>
$(document).ready(function () {
  $('#test').click();  //or  $('#test').trigger('click');
  $('#test').click(function(e){
    e.preventDefault();
    alert('here');
    window.location.href = $(this).attr('href'); //redirect to specified href
  });
});
</script>

.click() doesn't actually send a click event.

What .click() does is define something that happens when you click on the element.

You need to use to trigger the DOM element click

$('#test').get(0).click();

Use .get() , It retrieve the DOM elements matched by the jQuery object. As .click() will trigger the element click event handler. It will not actually click the element.

Using simple Vanialla JS

document.getElementById('test').click()

DEMO

Your #test link should be bound to a function, eg:

$(document).ready(function () {

  //do something on test click
  $('#test').on("click", alert());

 //click test
  $('#test').click();
});

http://jsfiddle.net/ub8unn2b/

Here click event is triggered ie click event is fired on page load but you can not load href by just triggering the click event,for that you can use

window.location.href = " http://www.google.com ";

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