2012-11-02 27 views
3

其實我的問題是不同的。如何在jQuery中調用onfocus事件的函數

我在下面這個小盒子裏調用了form中第一個元素的.focus事件的函數。

 $(".tbox :input:visible:enabled:first").focus(function() { 
      tabIndexForm(); 
     }); 

這是工作完美,但這是取代我自己的函數onFocus事件調用我手動設置的第一個元素的形式。這個怎麼做。我的形式是:

<form name="exampleform"> 
    <input type="text" name="a" onfocus="somefunction();"/> 
    <input type="text" name="b"/> 
    </form> 

現在,當我打開小框的tabIndexForm功能完美通話,但somefunction()不工作,因爲我覺得tabIndexForm替換該功能。如何更新下面的代碼以同時工作。

  $(".tbox :input:visible:enabled:first").focus(function() { 
      tabIndexForm(); 
     }); 

重要:我不能叫「somefunction()」中tinybox.js,因爲這是所有小盒子常見。

+0

功能是正確的,可能你正在做一些其他的事情是錯的。使用開發工具和瀏覽器來查看它們。 – totten

+0

確保你的函數可以訪問,並且如果可能的話在你定義它的地方顯示 – Adil

回答

1

這應該工作:

var elem = $(".tbox :input:visible:enabled:first"); 
var oldFunc = elem[0].onfocus; 
elem.focus(function() { 
    if(typeof oldFunc == 'function') oldFunc.call(elem[0]); 
    tabIndexForm(); 
}); 

入住這演示http://jsfiddle.net/8JbvY/

+0

不工作..... –

2

'專注' 功能/結合/事件處理程序的元素。

嘗試新的'on'函數,其中/添加/一個事件處理程序。

$(".tbox :input:visible:enabled:first").on('focus', function() { 
     tabIndexForm(); 
}); 

編輯第一次嘗試不起作用。

這應該更好的工作:

$(".tbox").on('focus', ":input:visible:enabled:first", function() { 
     tabIndexForm(); 
}); 

這樣的事件處理函數不是附屬的元素,所以它不會覆蓋舊的。

+0

這種形式的on()函數綁定了一個處理函數,就像'focus()'一樣。 –

+0

我沒有嘗試,我只是看着文檔,注意到不同的措辭。 – lyle

+0

我想在onfocus上追加tabIndexForm()而不是替換之前的 –

1

從你的元素中取出onfocus屬性:

<form name="exampleform"> 
    <input type="text" name="a"/> 
    <input type="text" name="b"/> 
</form> 

,改變你的JavaScript來:

$(".tbox input[name='a']").focus(somefunction); 

$(".tbox :input:visible:enabled:first").focus(function() { 
    tabIndexForm(); 
}); 

這也與你的事件處理程序處理爲您保持邏輯的更合適的方法在一個地方。

+0

實際上我不能添加這行$(「。tbox input [name ='a']」)。focus(somefunction);在tinybox.js中。這並不常見! –

+0

@ManishJangir爲什麼不呢?這與您的其他事件處理程序有何不同? – Curt