簡體   English   中英

如何在jquery中調用onfocus事件上的函數

[英]How to call a function on onfocus event in jquery

其實我的問題是不同的。

我在我的小盒子里調用了第一個元素元素的.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();
         });

重要提示:我不能在tinybox.js中調用“somefunction()”,因為這對所有小盒子來說都很常見。

'focus'函數/將/事件處理程序綁定到元素。

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

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

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

這應該更好:

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

這樣,事件處理程序沒有附加到元素,因此它不會覆蓋舊元素。

這應該工作:

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/

從元素中刪除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();
});

這也是處理事件處理程序的一種更簡潔的方法,因為您將邏輯保存在一個位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM