2010-10-12 73 views
1

我試圖在關閉瀏覽器時模擬h:commandButton中的onclick事件。模擬鉻中的onclick事件問題

這裏是我的代碼:

<body onBeforeUnload='closingBrowser()'> 


function closingBrowser() { 
    document.getElementById('main:commandButtonHidden').onclick(); 
    return false; 
} 

此javascript函數調用它有這個定義與我的按鈕相關的功能:

<h:commandButton id="commandButtonHidden" 
    value="checkPasswords().Login" 
    onclick="javascript:checkPasswords();" actionListener="#{init.closingBrowser}" /> 

和checkPasswords():

function checkPasswords() { 
    alert("checkPasswords"); 
    return true; 
} 

這個函數沒有什麼意思,因爲我想要的是我的actionListener中的函數。

這在IE和FF中非常適用,但不適用於Chrome或Opera。

警報總是會在所有瀏覽器中觸發,但actionListener NO只在IE和FF中無效。

有人對此有所瞭解。

感謝

+0

什麼是H:的commandButton? – 2010-10-12 19:55:08

+0

你能更清楚嗎?有什麼不對。該代碼在IE和FF中可以正常工作,actionListener不會在Chrome和Opera中觸發,但是如果直接點擊該按鈕,則可以在4個瀏覽器中完美工作。謝謝。 – 2010-10-15 18:13:19

回答

0

野生猜測:嘗試發射的不是訪問onclick回調click事件。

document.getElementById('main:commandButtonHidden').click(); 
0

我在搜索此問題的解決方案時發現此問題。我希望它不是太適合你晚,但我所做的:

(用jQuery)

var element = jQuery("#" + elementid); 
if (element.length > 0 && element[0].click == null) 
{ 
    element[0].click = function() 
    { 
     var mouseEvent = document.createEvent("MouseEvent"); 
     mouseEvent.initMouseEvent("click", true, true, window, 0, 
     element.offset().left + window.screenX, element.offset().top + window.screenY, 
     element.offset().left, element.offset().top, false, false, false, 0, null); 
     element[0].dispatchEvent(mouseEvent); 
    }; 
} 

,如果你不想使用jQuery(你不需要客戶端/屏幕的x/y共ORDS)

簡單地嘗試:

var mouseEvent = document.createEvent("MouseEvent"); 
mouseEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, 0, null); 
var element = document.getElementById('main:commandButtonHidden'); 
element.dispatchEvent(mouseEvent); 

從:https://developer.mozilla.org/en/DOM/document.createEvent