2010-09-21 17 views
0

即時試圖找出如何觸發從一個JavaScript函數的控件的事件觸發控制事件(不接觸實際控制本身)通過javascript

說我有這個文本框...

<input type="text" value="" id="my_textbox" onclick="alert('!');" />

然後說我試圖調用通過JavaScript的onclick事件...

function TriggerTextboxOnClick()
{
  //... call the onclick event of 'my_textbox'
}

p.s.我實際上並沒有試圖彈出一個警告框,我已經簡化了它爲了插圖的緣故

回答

1

Bouke's solution works。

在一般情況下,你可能想要做財產以後這樣的,而不是一個很好的做法:

<input id="my_textbox" onclick="my_textbox_onClick()" /> 
... 
function commonLogic() { 
    // Logic that's common to both the onclick event and the *other* code 
} 

function my_textbox_onClick() { 
    // This function should only contain logic that is triggered by a click on the textbox 
    commonLogic(); 
} 
+0

雖然我的解決方案的工作原理,從設計的角度來看,這將是一條路。 – bouke 2010-09-21 11:58:00

1

幾件事情:

  • 通過內嵌做成才onclick屬性,你已經有了在你的例子中不是最好的方法。在腳本塊中附加事件處理程序對於可訪問性和清潔,可維護的代碼更好。
  • 如果您正在使用像jQuery這樣的庫,然後讓庫爲您處理。看看下面的代碼:

//assuming using jQuery

$('#my_textbox').click(function(){ 
    //do stuff here 
}); 


//firing the event in some other function 
function TriggerTextBoxOnClick(){ 
    //do stuff here 

    $('#my_textbox').click(); 

} 

參考:內聯單擊處理更多信息:http://www.quirksmode.org/js/events_early.html

你可以做一樣的jQuery代碼與普通的舊JS太:

element.onclick = doSomething; 
if (element.captureEvents) element.captureEvents(Event.CLICK); 

閱讀此處以獲取有關使用普通JS執行此操作的更多信息:http://www.quirksmode.org/js/introevents.html