简体   繁体   English

无法在页面加载时可靠地添加事件监听器

[英]Can't add event listener at page load reliably

I can't seem to add these event listeners at page load reliably. 我似乎无法可靠地在页面加载时添加这些事件侦听器。 Some of the listeners work from the beginning, but others only work after a few clicks. 有些监听器从一开始就起作用,但是其他的只有单击几次才能起作用。 What might be wrong? 可能是什么问题? Could the problem be that I'm mixing native JS with jQuery? 问题可能是我将本机JS与jQuery混合了吗?

<script>
$(document).ready(function() {

function resetValidation() {
  jQuery('#contact-form').validate().resetForm();
};

function resetFormFields() {
  document.getElementById('contact-form').reset();
};

function removeValidationClasses() {
  jQuery('.control-group').removeClass('success').removeClass('error');
};

function changeHeaderToAdd() {
  document.getElementById('contactModalLabel').innerText = 'Add Contact';
};

function changeHeaderToUpdate() {
  document.getElementById('contactModalLabel').innerText = 'Update Contact';
};

function clearContactId() {
  document.getElementById('contactId').value = '';
};

  var ab = document.getElementById('addContactBtn');
  if (ab.addEventListener) {
    ab.addEventListener('click', resetValidation, false);
    ab.addEventListener('click', resetFormFields, false);
    ab.addEventListener('click', removeValidationClasses, false);
    ab.addEventListener('click', changeHeaderToAdd, false);
    ab.addEventListener('click', clearContactId, false);
  } else {
    ab.attachEvent('onclick', resetValidation);
    ab.attachEvent('onclick', resetFormFields);
    ab.attachEvent('onclick', removeValidationClasses);
    ab.attachEvent('onclick', changeHeaderToAdd);
    ab.attachEvent('onclick', clearContactId);
  };
  var ub = document.getElementById('updateContactBtn');
  if (ub.addEventListener) {
    ub.addEventListener('click', resetValidation, false);
    ub.addEventListener('click', resetFormFields, false);
    ub.addEventListener('click', removeValidationClasses, false);
    ub.addEventListener('click', changeHeaderToUpdate, false);
  } else {
    ub.attachEvent('onclick', resetValidation);
    ub.attachEvent('onclick', resetFormFields);
    ub.attachEvent('onclick', removeValidationClasses);
    ub.attachEvent('onclick', changeHeaderToUpdate);
  };
});
</script>

Solved! 解决了!

The JS was fine. JS很好。 However, since #updateContactBtn was created dynamically (one for each contact on the page), the problem was caused by the presence of nonunique id's. 但是,由于#updateContactBtn是动态创建的(页面上的每个联系人一个),因此该问题是由于存在非唯一ID引起的。 Only the first instance of #updateContactBtn worked. #updateContactBtn的第一个实例有效。

I changed #updateContactBtn to .updateContactBtn . 我将#updateContactBtn更改为.updateContactBtn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM