0

我在使用复选框时遇到问题,单击该复选框时会将我的“联系人”对象的属性从 0 切换到 1。

该复选框是生成的包含所有对象详细信息的 DIV 的一部分。我要切换的属性称为“切换”。

我试图实现的是,当单击复选框时,它会执行 UpdateStatus() 方法,并将对象的“ID”作为参数传入。然后循环遍历数组中的所有对象以匹配对象的“ID”。

问题是它会切换每个对象的“切换”属性,而不仅仅是我试图定位的对象。

使用复选框生成 div 的代码

Contact.prototype.generateDiv = function(){

          divid = divid + 1;
          buttonid = buttonid + 1;
         var control = [];
         control[0] = divid;
         control[1] = buttonid;
         var mapLocation = " ";
         myControls.push(control);

    if(this.daysUntil<=14){  //This checks to see if the contacts birthday is within 7 days or less,and creates a warning flag variable so we can display a warning flag
        birthdayFlag = "<img src=resources/birthday.png>"
    }else{
        birthdayFlag = " "
    };

    if(this.post){ // this checks to see if there is a value in the Postcode attribute, if not it will set the map location to the address entered
      mapLocation = this.post;
    }else{
      mapLocation = this.address;
    }


    var childDiv =
                "<div class='parentDiv'>" +
                this.firstName + " " + this.surname + " " + birthdayFlag + "<input type='checkbox' onclick='updateStatus(this.ID)'>" + " " +  "<button class='btnForDiv' id='" + buttonid + "'" + " > Click to Expand </button>" +
                "<div class='childDiv'  id='" +  divid  + "' " +  ">" + "<img class=map src='http://maps.google.com/maps/api/staticmap?scale=1&center=" + mapLocation + "&zoom=14&size=500x350&maptype=hybrid&markers=size:normal|color:RED|label:C|" + mapLocation + "&sensor=false' style='float: right;border-style:groove'>" +
                "&nbsp" + "<span style='color:#5f9ea0';> Surname: </span>"  + "<br> &nbsp&nbsp&nbsp&nbsp" + this.surname +
                "<BR> &nbsp" + "<span style='color:#5f9ea0';> First Name:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.firstName +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Date Of Birth:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.days + "/" +  this.months + "/" + this.years +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Telephone Number:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.phone +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.address + " " + this.post +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Email Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.email +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Group:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.group +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Days Until Birthday:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.daysUntil +
                "</div>" + "</div>" + "<HR width=1000px>"  + "<BR> ";
    return childDiv;

应该切换“toggled”属性的代码

var updateStatus = function(thisID){
    alert("firing");
    for (i = 0; i < contacts.length; i += 1) {
        if (thisID = contacts[i].ID){
            if (contacts[i].toggled = "0"){
                contacts[i].toggled = "1";
            }else{
                if (contacts[i].toggled = "1"){
                    contacts[i].toggled = "0";
                }
            }
        }
    }

}

以及需要的整个代码

var surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ;  //Declaring variables for the fields

var Contact = function(surname,firstName,date, phone , address , post, email, group, imglink){
    this.surname = surname ;
    this.firstName = firstName ;
    this.birthdayDate = new Date (date) ;
    this.phone = phone;
    this.address= address;
    this.email = email;
    this.post = post;
    this.group = group;
    this.toggled = "0" ;
    this.ID = "";

}

var contacts = [];
upcomingBirthdays = [];
divid = 0;
buttonid = 1000;
mapid = 100;
myControls = [];


var getDate = function() {

    for (var i= 0, j=contacts.length;i<j;i++){
        var y = contacts[i].birthdayDate.getFullYear();
        var m = contacts[i].birthdayDate.getMonth();
       var d = contacts[i].birthdayDate.getDate();
        contacts[i].days = d;
        contacts[i].months = m + 1;
        contacts[i].years = y ;
        var today = new Date() ;
        var ty = today.getFullYear();
        contacts[i].bdThisYear = new Date(ty,m,d, 0 , 0 , 0);

    }
}


var daysUntilBirthday = function(){
    for (var i= 0, j=contacts.length;i<j;i++){
        var today = new Date() ;
            contacts[i].daysUntil = Math.round((contacts[i].bdThisYear - today ) /1000/60/60/24+1);
            if (contacts[i].daysUntil <= 0){
            contacts[i].daysUntil =  contacts[i].daysUntil + 365 ;
        }
    }
}

var birthdayCheck = function(){
    for (var i= 0, j=contacts.length;i<j;i++){
        birth = "\n" + contacts[i].firstName + " " + contacts[i].surname + " has a birthday in " + contacts[i].daysUntil + " days" ;
        if(contacts[i].daysUntil <= 14){
            upcomingBirthdays.push (birth);
        }
    }
    if(upcomingBirthdays.length > 0){
        alert(upcomingBirthdays);
    }

}

Contact.prototype.generateDiv = function(){

          divid = divid + 1;
          buttonid = buttonid + 1;
         var control = [];
         control[0] = divid;
         control[1] = buttonid;
         var mapLocation = " ";
         myControls.push(control);

    if(this.daysUntil<=14){  //This checks to see if the contacts birthday is within 7 days or less,and creates a warning flag variable so we can display a warning flag
        birthdayFlag = "<img src=resources/birthday.png>"
    }else{
        birthdayFlag = " "
    };

    if(this.post){ // this checks to see if there is a value in the Postcode attribute, if not it will set the map location to the address entered
      mapLocation = this.post;
    }else{
      mapLocation = this.address;
    }


    var childDiv =
                "<div class='parentDiv'>" +
                this.firstName + " " + this.surname + " " + birthdayFlag + "<input type='checkbox' onclick='updateStatus(this.ID)'>" + " " +  "<button class='btnForDiv' id='" + buttonid + "'" + " > Click to Expand </button>" +
                "<div class='childDiv'  id='" +  divid  + "' " +  ">" + "<img class=map src='http://maps.google.com/maps/api/staticmap?scale=1&center=" + mapLocation + "&zoom=14&size=500x350&maptype=hybrid&markers=size:normal|color:RED|label:C|" + mapLocation + "&sensor=false' style='float: right;border-style:groove'>" +
                "&nbsp" + "<span style='color:#5f9ea0';> Surname: </span>"  + "<br> &nbsp&nbsp&nbsp&nbsp" + this.surname +
                "<BR> &nbsp" + "<span style='color:#5f9ea0';> First Name:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.firstName +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Date Of Birth:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.days + "/" +  this.months + "/" + this.years +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Telephone Number:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.phone +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.address + " " + this.post +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Email Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.email +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Group:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.group +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Days Until Birthday:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.daysUntil +
                "</div>" + "</div>" + "<HR width=1000px>"  + "<BR> ";
    return childDiv;

}

var updateStatus = function(thisID){
    alert("firing");
    for (i = 0; i < contacts.length; i += 1) {
        if (thisID = contacts[i].ID){
            if (contacts[i].toggled = "0"){
                contacts[i].toggled = "1";
            }else{
                if (contacts[i].toggled = "1"){
                    contacts[i].toggled = "0";
                }
            }
        }
    }

}

var assignID = function(){
    for (i = 0; i < contacts.length; i += 1) {
      contacts[i].ID = "" + i + "" ;
    }
}

var removeContacts = function () {
    for (i = 0; i < contacts.length; i += 1) {
        if (contacts[i].toggled = "1"){
            contacts.splice(i,1);
        }
    }
    updateList();

}


var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
        if(surnameField.value){
            a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
            contacts.push(a);
        }else{ alert("Please complete all fields")}

}

var clearUI = function(){
    var white = "#fff";
    surnameField.value = "";
    surnameField.style.backgroundColor = white;
    firstNameField.value = "";
    firstNameField.style.backgroundColor = white;
    birthdayField.value="";
    birthdayField.style.backgroundColor = white;
    phoneField.value = "";
    phoneField.style.backgroundcolor = white;
    addressField.value = "";
    addressField.style.backgroundcolor = white;
    postField.value = "";
    postField.style.backgroundcolor = white;
    emailField.value = "";
    emailField.style.backgroundcolor = white;
    groupField.value="";
    groupField.style.backgroundcolor = white;

}

var updateList = function(elements){
    assignID();
    myControls = []
    var tableDiv = document.getElementById("parentDiv"),
        cDiv = "<BR>" ;

    for (var i= 0, j=elements.length;i<j;i++){
        var cntct = elements[i];
        cDiv += cntct.generateDiv();
    }

    tableDiv.innerHTML = cDiv;
    getDate();
    daysUntilBirthday();
    saveContacts();
}

var add = function(){
;
    addContact(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField, imgField);
    clearUI();
    daysUntilBirthday();
    getDate();
    updateList(contacts);
    updateList(contacts);
};

var saveContacts = function(){
    var cntcts = JSON.stringify(contacts);
    if (cntcts !==""){
        localStorage.contacts = cntcts;
    }else{
        alert("Could not save contacts");
    }
}

var loadContacts = function(){
    var cntcts = "";
    if(localStorage.contacts !== undefined){
        cntcts = localStorage.contacts;
        contacts = JSON.parse(cntcts);
        var proto = new Contact();
        for (var i=0; i<contacts.length; i++){
            var cntct = contacts[i]
            cntct.__proto__ = proto;
            cntct.birthdayDate = new Date(cntct.birthdayDate);
        }
    }
}

var clearContacts = function(){
    contacts = [];
    updateList(contacts);

}

var sort_by = function(field, reverse, primer){

    var key = function (x) {return primer ? primer(x[field]) : x[field]};

    return function (a,b) {
        var A = key(a), B = key(b);
        return (A < B ? -1 : (A > B ? 1 : 0)) * [1,-1][+!!reverse];
    }
}

var sortBySurname = function(){
    contacts.sort(sort_by('surname', false, function(a){return a.toUpperCase()}));
    updateList(contacts)
}

var sortByFirstname = function(){
    contacts.sort(sort_by('firstName', false, function(a){return a.toUpperCase()}));
    updateList(contacts)
}

var sortByGroup= function(){
    contacts.sort(sort_by('group', false, function(a){return a.toUpperCase()}));
    updateList(contacts)
}

var sortByBirthday= function(){
    contacts.sort(sort_by('daysUntil', false, parseInt));
    updateList(contacts)
}

window.onload = function(){
    loadContacts();
    updateList(contacts);
    surnameField = document.getElementById("surname");
    firstNameField = document.getElementById("firstName")
    birthdayField = document.getElementById("birthday");
    phoneField = document.getElementById("phone");
    addressField = document.getElementById("address");
    postField = document.getElementById("post");
    emailField = document.getElementById("email");
    groupField = document.getElementById("group");
    imgField = document.getElementById("image");
    addButton = document.getElementById("addButton");
    addButton.onclick = add;
    delButton = document.getElementById("delButton");
    searchField = document.getElementById("searchField");
    searchButton = document.getElementById("searchButton");
    //searchButton.onclick = doSearch();
    //delButton.onclick = removeContacts();
    sortSurnameButton = document.getElementById("surnameSort");
    sortSurnameButton.onclick = sortBySurname;
    sortFirstNameButton = document.getElementById("firstNameSort");
    sortFirstNameButton.onclick = sortByFirstname;
    sortGroupButton = document.getElementById("groupSort");
    sortGroupButton.onclick = sortByGroup;
    birthSortButton = document.getElementById("birthSort");
    birthSortButton.onclick = sortByBirthday;
    clearUI();
    birthdayCheck();

}
4

1 回答 1

0

过度复杂切换器的错误:试试这个:

if (thisID === contacts[i].ID){  //<- HERE WAS MISTAKE - single =
    contacts[i].toggled=contacts[i].toggled==="1"? "0": "1"
}

最好按 id 索引您的联系人Object以避免按 id 循环...或者在访问数组时仅使用 id,您可以使用此函数生成类似 UUID。

您可以使用以下方法实现:

var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
        if(surnameField.value){
            a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
            contacts[GUID()]=a;
        }else{ alert("Please complete all fields")}

}

对象将看起来像:

{ef9cffdc-9132-af78-6147-6bfc2cb247dc: {object data}, 405e61ae-881e-4b11-eab6-2f2355ca54ae  : {object data},}

并且可以通过objects[ID]; 单个对象删除轻松访问,如下所示delete(objects[ID]):循环将看起来:

for (var id in objects) {
   var object=objects[id];
}

够容易吗?

于 2012-12-09T01:42:24.700 回答