选择在Javascript中提交时已分配的项目类

时间:2015-03-02 18:56:44

标签: javascript

您好我正在尝试选择已在jQuery提交时分配的类。我无法选择班级。

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

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

这是我想要实现的一个例子。

1 个答案:

答案 0 :(得分: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