Jquery点击函数未触发点击

Jquery click function not triggering a click

本文关键字:函数 Jquery      更新时间:2023-09-26

我有一个简单的HTML页面:

<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>

我想在加载页面时触发名为test的元素上的单击事件。实际的代码实际上比这更复杂,但这个非常基本的示例不起作用。我查看了控制台日志,没有任何通知。

您需要使用来触发DOM元素点击

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

使用.get(),它检索jQuery对象匹配的DOM元素。由于.click()将触发元素单击事件处理程序。它实际上不会单击元素。

使用简单的香草JS

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

DEMO

.click()实际上并不发送点击事件。

click()所做的是定义当您单击元素时发生的事情。

您正在触发的.click()是正确的,但您错过了'#test'的点击事件,如图所示:

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

现在,您完整的jquery代码如下所示:

<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>

您的#测试链接应该绑定到一个函数,例如:

$(document).ready(function () {
  //do something on test click
  $('#test').on("click", alert());
 //click test
  $('#test').click();
});

http://jsfiddle.net/ub8unn2b/

这里触发点击事件,即点击事件在页面加载时触发,但您不能仅通过触发点击事件来加载href,为此您可以使用

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