这是我的例子:
$.ajax({
type: "POST",
url: "some.php",
data: "fname=John&lname=Due",
success: function(result){
$('#content').html('Label 1: <input name="quantity[]" class="quantity"> Label 2: <input name="quantity[]" class="quantity">');
}
});
并且js验证数量
$(".quantity").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
最佳答案
.html()
是一个函数,其中要设置为 new html
的参数在调用时传递,除非 .html(function(index, html){})
使用模式,其中 new html
在函数回调中 return
;不像 .innerHTML
那样设置为属性值。替补
$('#content').html('Label 1: <input name="quantity[]" class="quantity"> Label 2: <input name="quantity[]" class="quantity">');
对于
$('#content').html = 'Label 1: <input name="quantity[]" class="quantity"> Label 2: <input name="quantity[]" class="quantity">';
<小时/>
使用事件委托(delegate)将 keydown
事件附加到动态创建的 .quantity
元素;或在创建元素时附加事件
function handleKeydown(e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
$('#content')
.html('Label 1: <input name="quantity[]" class="quantity"> Label 2: <input name="quantity[]" class="quantity">')
.find(".quantity")
.keydown(handleKeydown);
关于javascript - ajax加载内容后无法验证数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136716/