2013-06-28 55 views
1

使用JavaScript的onKeypress嘗試在返回後調用函數。 這不起作用,因爲該字段由於驗證號碼而尚未完成。返回後的javascript onkeypress調用函數

onKeyPress="return numbersonly(event, false); 
      anotherfunction();" 

是什麼讓這個棘手的是必須發生的返回之前「anotherfunction()」之稱。

+0

_「試圖在返回後嘗試調用函數?」_。不可能,這是常見的編程概念。一個'return'退出函數... – elclanrs

+0

是否有jQuery解決方法? – user2533570

+0

嵌入式JavaScript ... brrr .... –

回答

0

這將在函數返回之後調用anotherFunction():

onKeyPress="setTimeout(anotherFunction, 0); return numbersonly(event, false);"> 

它比Barmar的答案稍有不同的行爲。在調用numbersOnly之後,但在事件處理程序返回之前,他調用anotherFunction。 Mine會在事件處理程序返回後調用另一個函數。兩者都適用於不同的情況。

需要注意的是,如果你想傳遞參數給anotherFunction你應該這樣做:

onKeyPress="setTimeout(function(){anotherFunction(1,2,3);}, 0); return numbersonly(event, false);"> 
+0

非常聰明的解決方案。謝謝 – user2533570

+0

@ user2533570沒問題:)很高興能幫到您 – Paulpro

1

使用此:

onkeypress="if (numbersonly(event, false)) {anotherfunction(); return true;} else {return false}" 

由於長聯JavaScript這樣的錯誤我,我會提出這個出一個功能:

function maybe_another(event) { 
    if (numbersonly(event, false)) { 
     anotherfunction(); 
     return true; 
    } else { 
     return false 
    } 
} 

,然後使用:

onkeypress="return maybe_another(event)" 
輸入元素中的

+0

這與我已經接近,但沒有引用解決。 onKeypress發生在數量字段中。 「anotherfunction()」根據數量重新計算總和。它似乎是一個點擊。例如,我打1,沒有任何反應,然後打2,它計算使用1作爲數量而不是12。 – user2533570

+1

聽起來像你應該使用'onkeyup'而不是'onkeypress'。在將新字符添加到輸入之前調用按鍵處理程序,之後調用該處理程序。 – Barmar

+0

我添加了一個使用if的新解決方案。 – Barmar

0

試着這麼做:

function E(e){ 
    return document.getElementById(e); 
} 
function FirstFunction(event, truthiness){ 
    return 'Truthiness was set to '+truthiness; 
    //of course you must really be trying to run something from the Event 
    //Object or you don't need the event argument in this function or the 
    //keyup function below 
} 
function SecondFunction(e){ 
    E(e).innerHTML = this.value; 
} 
E('txt').onkeyup = function(ev){ 
    var e = ev || window.event; 
    E('out1').innerHTML = FirstFunction(ev, false); 
    SecondFunction.call(this, 'out2'); 
} 

如果你不明白callthis然而,這很好。重點是向您展示您可以在分配給您的事件偵聽器的函數中放入儘可能多的函數。這種編程風格可以保存在外部JavaScript文件中,該文件可以緩存在用戶瀏覽器中。有些人稱它爲Jnobtrusive JavaScript,因爲它不在你的HTML中。另一種方法,如果您由於某種原因,是沒有意義的,堅持用生硬的JavaScript,是將SecondFunction傳遞到了firstFunction和你return值之前執行它,如:

function FirstFunction(func, funcArg, anotherFunc, anotherFuncArg){ 
    func(funcArg); 
    anotherFunc(anotherFuncArg); 
} 
function SecondFunction(e){ 
    E(e).innerHTML = 'this is just a test'; 
} 
<input type='text' onkeyup='FirstFunction(SecondFunction, "out", function(){console.log = "You can use an Anonymous Function the same way"})' name='txt' id='txt' /> 

這告訴你如何可以傳遞未執行的函數作爲參數。稍後使用該參數。 JavaScript中的函數名稱基本是可變的。在PHP中,你可以做相同類型的事情,只需要將你的函數改爲String即可。

大多數JavaScript程序員首選第一種方法。完整的例子請看下面的小提琴。

http://jsfiddle.net/PHPglue/3q4DC/4/