javascript - ajax加载内容后无法验证数量

标签 javascript php jquery ajax

这是我的例子:

$.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/

相关文章:

php - 当鼠标悬停在链接上时,创建网站预览吗?

php - AJAX登录无需重新加载页面

javascript - 如何将 html 表格保存为图像供客户保存在他们的计算机上

php - 为内页添加第二个侧边栏

javascript - 如何使用 PHP、AJAX 和 JS 的复选框来过滤类似产品?

javascript - 如何根据滚动位置逐步变换元素

javascript - Node.js 视频上传获取Codec

javascript - 类内可重用的事件监听器回调

javascript - Restangular 中的 RESTful 乐观锁定

php - 无法在 mac high sierra 的自制软件上找到 pcntl