2012-10-26 69 views
0

尝试使用这段代码模拟的对象上的点击,我在HTML注入该代码..jQuery的点击模拟不工作

<script type='text/javascript'> 
    $(window).load(function() { 
     $('#hellothere').click(); 
    }); 
</script> 

不wroking ......在所有!

+0

为什么不'$(文件)。就绪(函数(){...})'? – cdmckay

+0

“#hellothere”是什么类型的元素?你期望它做什么?运行附加的处理程序?导航到网址(如果超链接)? –

+0

http://jsfiddle.net/rrWhz/ ---它的工作......一切! – zerkms

回答

2

您应该使用ready()功能来运行代码时,DOM就绪 - http://api.jquery.com/ready/ - 该load()方法加载新的内容 - http://api.jquery.com/load/ - 和不正确,你的目的。然后,您可以使用trigger()在DOM对象上触发单击事件。

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

如果您阅读链接到的'.load()'doco,会看到还有一个['.load()'事件处理程序](http://api.jquery.com/load-event/ ) - jQuery根据传递的参数决定要执行哪个处理。 – nnnnnn

+0

我在发布问题之前也尝试了这一点,似乎没有任何工作。这是否有关系,我试图模拟点击的对象是一个textarea? –

+0

男人如果你有定义一个触发器,首先你必须定义该div的点击功能。像这样:$(document).ready(function(){$('#hellothere')。click(function(){//这里有一些函数}); //现在如果你想触发点击$( '#hellothere')。trigger('click');});'现在随着DOM的加载,你在click函数中定义的函数将自动运行.. – Heart

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); 
} 

正如你所看到的;如果没有参数被解析到该函数,它将触发点击事件。

所以使用.trigger(“click”)因为你会调用一个较少的函数。 https://stackoverflow.com/a/9666547/887539

PS:

这是一个很好的工具寻找到jQuery的源代码:http://james.padolsey.com/jquery/

+1

但'.click )'没有参数只是'.trigger('click')'的快捷方式。 – nnnnnn

+0

因为触发比单击更快,我已经更新了我的答案 –

+1

好的,如果性能_really_重要的是使用'.trigger()',但这并不能解释为什么OP的代码不工作... – nnnnnn