在对象属性上迭代addEventListener

时间:2018-03-12 17:10:14

标签: javascript loops object dom

我正在尝试向多个DOM元素添加一个事件侦听器,因此我创建了一个包含所有这些元素的对象。现在我想弄清楚如何遍历这个对象,这样我就可以为所有这些对象添加相同的事件监听器。我可以在很长的路上做到这一点,但我想让事情变得更加紧凑和简洁。我试图使用for..in循环,但是出错了。

我的代码:

var realID;

function getFormId(){

var formID = document.querySelector("div[id^=PC]").id;
var actualID = formID.split("");
realID = actualID[0] + actualID[1] + actualID[2] + actualID[3] + actualID[4] + actualID[5];

} getFormId(realID);

var boxes = {
  titleBox: document.getElementById(realID + "_DonationCapture1_cboTitle"),
  firstNameBox: document.getElementById(realID + "_DonationCapture1_txtFirstName"),
  middleNameBox: document.getElementById(realID + "_DonationCapture1_txtMiddleName"),
  lastNameBox: document.getElementById(realID + "_DonationCapture1_txtLastName"),
  country: document.getElementById(realID + "_DonationCapture1_AddressCtl_dd_Country"),
  address: document.getElementById(realID + "_DonationCapture1_AddressCtl_tb_AddressLine"),
  city: document.getElementById(realID + "_DonationCapture1_AddressCtl_tb_CityUS"),
  state: document.getElementById(realID + "_DonationCapture1_AddressCtl_dd_StateUS"),
  zip: document.getElementById(realID + "_DonationCapture1_AddressCtl_tb_ZipUS"),
  phone: document.getElementById(realID + "_DonationCapture1_txtPhone"),
  email: document.getElementById(realID + "_DonationCapture1_txtEmail"),
  cardName: document.getElementById(realID + "_DonationCapture1_txtCardholder"),
  cardNumber: document.getElementById(realID + "_DonationCapture1_txtCardNumber"),
  cardType: document.getElementById(realID + "_DonationCapture1_cboCardType"),
  cardExpirationOne: document.getElementById(realID + "_DonationCapture1_cboMonth"),
  cardExpirationTwo: document.getElementById(realID + "_DonationCapture1_cboYear"),
  cardSecurity: document.getElementById(realID + "_DonationCapture1_txtCSC")
}

for ( var box in boxes ){
  box.addEventListener("click", function(){
    if ( monthlyButton.classList.contains("blue-button") || yearlyButton.classList.contains("blue-button") ){

    } else {
      monthlyButton.classList.remove("lite-grey-button");
      monthlyButton.classList.add("red-button");

      yearlyButton.classList.remove("lite-grey-button");
      yearlyButton.classList.add("red-button");
    }
  }, false);
}

1 个答案:

答案 0 :(得分:0)

更改for循环以引用值而不是box对象中的键。

for (var box in boxes) {
    boxes[box].addEventListener("click", function() {

      if (monthlyButton.classList.contains("blue-button") || earlyButton.classList.contains("blue-button") ) {

    } else {
      monthlyButton.classList.remove("lite-grey-button");
      monthlyButton.classList.add("red-button");

      yearlyButton.classList.remove("lite-grey-button");
      yearlyButton.classList.add("red-button");
    }   }, false); }