2015-03-02 31 views
-1

嗨我正在尝试选择已在jQuery提交中分配的类。我无法选择课程。选择已用Javascript提交的项目类别

$('form.ajax').on('submit', function(e) { 
    $.ajax({ 
    success: function(data) { 
    $("#" + key).addClass("missed"); 
}); 

$('input.missed').click(function() { 
    alert("Clicked"); 
}); 

这是我试图实现的一个例子。

+1

'成功'回调缺少右括号 – DontVoteMeDown 2015-03-02 18:58:37

+1

...和缺少'});'在阿贾克斯调用 – acbabis 2015-03-02 19:00:23

+0

而且您不取消提交操作。 – epascarello 2015-03-02 19:08:09

回答

0

假设问题是“如何在提交事件之后向单元添加点击处理程序?”那么答案可能是您的成功回调有几个语法错误,您的缩进表明您以不正确的顺序管理DOM。为了说明这里是一些注释代码:

$('form.ajax').on('submit', function(e) { 
    // Prevent an actual submission in favor of AJAX 
    e.preventDefault(); 
    // Spawn an AJAX request to http://ecample.com/api/form_validator 
    $.ajax({url: 'http://example.com/api/form_validator'}) 
    // Once we have a success response *then* do the following. 
    .then(function(response) { 
     // Use the response from the server to iterate of the keys array. 
     $.each(response.keys, function(i, key) { 
     // add the missing class to the element that matches the key. 
     $('#element-' + key).addClass('missed'); 
     }); 
    }); 
}); 

// Assign a click event to the entire form but filter it by 'input.missing' 
// this way whe an input does have the missingf class the click will happen 
// otherwise it is ignored. This is call event delegation. 
$('form.ajax').on('click', 'input.missed', function(e) { 
    alert('Clicked'); 
}); 

这就是呼叫event delegation

+0

我为示例目的创建了代码,只是为了说明在成功或不成功的submitino之后我想实现的目标。我面临的问题是,通过第一个实例的代码添加的类无法通过第二个实例找到。 – 2015-03-03 10:17:36

+0

似乎你还没有读过上面的答案。没有你说的第二个例子。你提供的代码没有这样的。即使它的执行仍然失灵!可以使用jQuery的'live()'方法的事件委托。 – Sukima 2015-03-03 14:10:33

+0

有没有更简单的方法呢? (“form.ajax”)。on(“keyup”,“input [data-invalid ='true']”,function(e){ $(this).removeClass(“missed”); }) ; ($(this).val()===“)的函数(”form.ajax“)on(”focusout“,”input [data-invalid ='true' “){ $(this).addClass(”missed“); } }); (“form_ajax”)。on(“focusin”,“input [data-invalid ='true']”,function(e){ $(this).removeClass(“missed”); } ); – 2015-03-03 15:39:43