[英]onKeydown is not working when added dynamically
I am trying to append some html in my web page using jQuery. 我试图使用jQuery在我的网页中附加一些html。 My code is
我的代码是
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 is a function whose source code is 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;
}
Using these function, only numbers can be entered in the text box. 使用这些功能,只能在文本框中输入数字。 When I assign some element like this
$("#some_elem").onKeyDown(isNumberKey)
then it is working correctly but i want to know why its not working in first case. 当我分配一些像这样的元素
$("#some_elem").onKeyDown(isNumberKey)
然后它正常工作,但我想知道为什么它在第一种情况下不起作用。
You have to delegate
the event. 您必须
delegate
该活动。 Use : 采用 :
$(document).on('keydown' , '.some-class', isNumberKey);
If you append
new elements
to your markup, the event
wont be binded on them. 如果
append
新elements
append
到标记,则event
不会绑定在它们上。 So you need to delegate it. 所以你需要委托它。
Use a class
instead of a id
. 使用
class
而不是id
。 Of course the class
need to be added to the appended
div
or , in this case, to the input
I guess. 当然这个
class
需要添加到appended
div
或者在这种情况下,需要添加到input
。
If you use $('.some-class').on('event', function(){})
the event will be attached only on existing elements that have .some-class
. 如果使用
$('.some-class').on('event', function(){})
,事件将仅附加在具有.some-class
现有元素上。 Using delegation will attacch the event
on any div
you want. 使用委托会将
event
附加到您想要的任何div
。
如果你想在HTML中伴随,请尝试更改下面的代码
onKeydown="isNumberKey()"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.