我試圖在使用jQuery的我的網頁中添加一些html。我的代碼是onKeydown在動態添加時無法正常工作
var s1 = "<div class='controls'><label class='inline labelspace'>Minimum Cart Value<input class='inline input-small' type='text' name='mincart' onKeydown=isNumberKey ></input></label>";
s1 += "<label class='inline labelspace'>Minimum No Of Items<input class='inline input-small' type='text' placeholder='Enter Integer' name='minitem' onKeydown=isNumberKey></input></label>" ;
s1 += "<label class='inline labelspace'>Location<input class='inline input-small' type='text' name='location' ></input></label>";
s1 += "<label class='inline labelspace'>Product Ids<input class='inline input-small' onKeydown=isValid type='text' name='products'></input></label></div>" ;
$("#lastrow").before(s1);
isNumberKey是一個函數,它的源代碼是
function isNumberKey(evt) {
console.log('coming to this');
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
} else
return true;
}
使用這些功能,只有數字可以在文本框中輸入。當我指定這樣的元素 $("#some_elem").onKeyDown(isNumberKey)
然後它工作正常,但我想知道爲什麼它不工作在第一種情況。
代碼並沒有一個名爲'onKeyDown'在jQuery的事件。我想你正在尋找'keydown'事件。 –
如果你想看看這應該如何工作,請在我的答案中查看演示。 。 – Givi