尝试使用此代码模拟对象的点击,我在html中注入此代码..
<script type='text/javascript'>
$(window).load(function() {
$('#hellothere').click();
});
</script>
根本不打算......
答案 0 :(得分:2)
您应该使用ready()
函数在DOM准备就绪时运行代码 - http://api.jquery.com/ready/ - load()
方法用于加载新内容 - http://api.jquery.com/load/ - 并且不正确为了你的目的。然后,您可以使用trigger()
触发DOM对象上的click事件。
// run when the DOM is loaded
$(document).ready(function(){
$('#hellothere')
// Set up the click event
.on('click', function(){ alert('you clicked #hellothere'); })
// Trigger the click event
.trigger('click');
});
答案 1 :(得分:0)
如果您尝试模拟对象的单击,则应使用触发器方法
$(function){
$('#hellothere').trigger('click');
});
以下是触发器上文档的链接:http://api.jquery.com/trigger/
这是点击方法的代码:
jQuery.fn.click = function (data, fn) {
if (fn == null) {
fn = data;
data = null;
}
return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
}
你可以看到;如果没有对函数解析参数,它将触发click事件。
所以使用.trigger(“click”)因为你会少调用一个函数。 https://stackoverflow.com/a/9666547/887539
PS:
这是查看jQuery源代码的好工具:http://james.padolsey.com/jquery/