2014-02-18 48 views
1

美好的一天。攔截點擊,做出一些行動,然後再傳播「點擊」

今天,它已被要求我開發一個JavaScript(jQuery)跟蹤成千上萬的網頁上的一些事件。

我必須攔截一些可點擊元素的點擊,進行一些調用,然後讓頁面一如既往地繼續工作。 例如,假設頁面上有一些文本輸入,一些複選框,一些鏈接和一個提交按鈕。

讓我們暫時忽略提交按鈕。我會稍後處理它。我有這樣的想法:

$(document).ready(function() { 
    $('input[type=button], input[type=submit], input[type=checkbox], button, a').bind('click', function(evt, check) { 
     //evt.preventDefault(); 

     console.log("id:"+ evt.target.id+", class:"+evt.target.class+", name:"+evt.target.name); 
     console.log (check); 

     evt.target.trigger('click', 'check'); 
    }); 
}); 

我不得不使用jquery 1.5,不能更新到沒有更多。

我猜測,這可能是staight前鋒,但上面返回代碼此錯誤:

id:terms, class:undefined, name:terms 
undefined //this is ok, the check variable will be used to distinguish real clicks from triggered ones. 

Uncaught TypeError: 
Object #<HTMLInputElement> has no method 'trigger' 
(anonymous function) 
E jquery-1.5.min.js 
d.event.handle jquery-1.5.min.js 
j.handle.l jquery-1.5.min.js 

我會忘了什麼......?提前致謝。

回答

2
$(evt.target).trigger 

evt.target by its self沒有jQuery包裝器。

這是顯着的:下面一行:

Object #<HTMLInputElement> has no method 'trigger' 

其中規定,你有一個HTMLInputElement的,而不是一個jQuery對象的對象。

此外,升級您的jQuery版本。 1.5非常過時,你缺少性能和關鍵功能。如果你能

+0

非常感謝,我測試並儘快接受答案。謝謝。 –

0

包裝evt.target到jQuery對象像$(evt.target).trigger(...)

1

絕對升級的jQuery。

我覺得mousedown聽衆可能會適合你:

jQuery的最新1.x的分支

$('button, input[type="checkbox"]').on('mousedown', function(e){ 
    alert(e.type); 
}); 

/* uncomment this and comment the top to see the difference 
$('button, input[type="checkbox"]').on('mouseup', function(e){ 
    alert(+e.type); 
}); 
*/ 

HTML

<button>Click Me</button> 
<br> 
<input type="checkbox"> 

JSfiddle

您無法同時使用mouseup,因爲當您在本示例中單擊警告框時它會關閉。

我認爲你應該沒有問題在mousedown上實現一個ASYNC AJAX調用,然後如果你想要的話,讓mouseup觸發另一個。如果你想計算你的用戶在釋放前持有鼠標的毫秒數,我想這會很有用。