嘗試使用這段代碼模擬的對象上的點擊,我在HTML注入該代碼..jQuery的點擊模擬不工作
<script type='text/javascript'>
$(window).load(function() {
$('#hellothere').click();
});
</script>
不wroking ......在所有!
嘗試使用這段代碼模擬的對象上的點擊,我在HTML注入該代碼..jQuery的點擊模擬不工作
<script type='text/javascript'>
$(window).load(function() {
$('#hellothere').click();
});
</script>
不wroking ......在所有!
您應該使用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');
});
如果您閱讀鏈接到的'.load()'doco,會看到還有一個['.load()'事件處理程序](http://api.jquery.com/load-event/ ) - jQuery根據傳遞的參數決定要執行哪個處理。 – nnnnnn
我在發佈問題之前也嘗試了這一點,似乎沒有任何工作。這是否有關係,我試圖模擬點擊的對象是一個textarea? –
男人如果你有定義一個觸發器,首先你必須定義該div的點擊功能。像這樣:$(document).ready(function(){$('#hellothere')。click(function(){//這裏有一些函數}); //現在如果你想觸發點擊$( '#hellothere')。trigger('click');});'現在隨着DOM的加載,你在click函數中定義的函數將自動運行.. – Heart
如果你試圖模擬對象上的點擊,您應該使用的觸發方式,
$(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/
爲什麼不'$(文件)。就緒(函數(){...})'? – cdmckay
「#hellothere」是什麼類型的元素?你期望它做什麼?運行附加的處理程序?導航到網址(如果超鏈接)? –
http://jsfiddle.net/rrWhz/ ---它的工作......一切! – zerkms