2010-09-23 107 views
2

我已經添加了stopPropagation,但是,我仍然連續得到兩個彈出窗口。這比以前更好,那裏有20個彈出窗口,點擊了一個元素....有沒有更好的方法,還是我錯過了什麼?Jquery:停止傳播?

$(top.document).ready(function() { 

    $("*").click(processAction); 

}); 

function processAction(e) { 
    var clicked = e.target; 
    e.stopPropagation(); 
    alert(clicked.tagName); 
    e.stopPropagation(); 
    switch (clicked) { 
    case "A": 
     //execute code block 1 
     break; 
    case "INPUT": 
     //execute code block 2 
     break; 
    default: 
     //code to be executed if n is different from case 1 and 2 
    } 
}; 
+0

你真的打算停止所有的默認操作上樹的每一個元素?你的stopPropagation調用是否應該放在case block中,而不是放在它們之前,這樣只有你明確處理的元素纔會停止傳播? – 2010-09-23 00:37:32

回答

3

我說絕對不要在每個元素上放置點擊處理程序。正如@Rin所述,您可以通過標籤或其他選擇器來分配它們。

如果你真的要這樣處理網頁上的所有點擊,我建議您將一個處理器上document,讓單擊事件冒泡了這一點。

這樣效率更高,不需要做e.stopPropagation()

例子:http://jsfiddle.net/y6hry/

$(top.document).ready(function() { 
     // All clicks on the page will bubble up to the document 
     // and fire the handler. 
    $(document).click(processAction); 
}); 

function processAction(e) { 
    var clicked = e.target; 
    alert(clicked.tagName); 
    switch (clicked.tagName) { 
    case "A": 
     //execute code block 1 
     break; 
    case "INPUT": 
     //execute code block 2 
     break; 
    default: 
     //code to be executed if n is different from case 1 and 2 
    } 
}; 
0

使用

$('*').each(map, function(key, value) { 
    $(this).click(processAction); 

}); 

代替;

+1

jQuery'.each()'只接受一個參數,那麼'map'參數是什麼?如果你使用'.each()',你會得到和問題中代碼相同的結果。 – user113716 2010-09-23 00:44:37

+0

聽起來像'$ .each()'和'$(...)。each()'混淆了我。 – 2010-09-23 01:43:05

0

我的小建議:用ainput替換*。現在你的代碼會更簡單,你可以刪除開關。 (我看到在切換你檢查什麼元素被點擊)。