0

我正在制作一个通讯录,每个新条目都会生成一个包含所有信息的 Div。我已经为每个生成的 div 提供了唯一的 ID,并为使用 Div 生成的每个按钮提供了唯一的 ID,但是我无法将按钮与 div 关联并允许它执行功能(例如切换可见性)分)。

非常感谢您提供的任何帮助,因为我很快就会因沮丧而秃顶。

更新了包含建议的代码

生成 DIV 和 Button 的代码:

 Contact.prototype.generateDiv = function(){

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

var childDiv =
            "<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
            this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
            "<div  id='" +  divid  + "' " +  "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
            "<br>" + "Surname: "  +  this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
            "Date Of Birth: " +  this.days + "/" +  this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
            "<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
            "<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" +  "</div>" +  "</div>"


        return childDiv  ;

}

整个代码

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){
    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.selected = false ;

}

var contacts = [];
divid = 0;
buttonid = 1000;
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 ;
        }
    }
}

Contact.prototype.generateDiv = function(){

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

    var childDiv =
                "<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
                this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
                "<div  id='" +  divid  + "' " +  "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
                "<br>" + "Surname: "  +  this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
                "Date Of Birth: " +  this.days + "/" +  this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
                "<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
                "<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" +  "</div>" +  "</div>"


            return childDiv  ;

}



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(){
    divid = 0;
    buttonid = 1000;
    myControls = []
    var tableDiv = document.getElementById("parentDiv"),
        cDiv = "<BR>" +  "<div align='center'> Click a contact to expand</div>" ;

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

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

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

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();

}

//var periodUpdate = function(){
//    setInterval(updateList, 10000);
//}




window.onload = function(){
    loadContacts();
    updateList();
    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");
    addButton = document.getElementById("addButton");
    addButton.onclick = add;
    delButton = document.getElementById("delButton");
    delButton.onclick = clearContacts;
    clearUI();
   // periodUpdate();
}

的HTML

<!DOCTYPE html>
<html>
<head>

    <script type="text/javascript" src="contacts.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="jquery-1.8.3.min.js">
    $(document).ready(function(){

        (".btnForDiv").on("click", function(){

    // get the ID of the button
    var id = $(this).prop("id");
    var divid;
    // now find the div Id related to this button
    for (var i = 0, len = myControls.length; i < len; i++){
    if (myControls[i][1] == id){
    divid = myControls[i][0];
    break;
    }
    }

    // you now have the div,so toggle it.
    $("#" + divid).toggle();

    });
    });
    </script>

    <div><title>Contacts Book</title></div>

</head>

<body>
<div class="information">
<heading><h1>Contacts Book</h1></heading>
</div>
<p><div class="information">Enter the contacts details below and click Add or select to view an existing contact.</div></p>
<hr>

<div class="entrydiv">
<table class="entryforms">
    <br>
    <tr>
        <td>Surname</td><td><input type="text" class="inputboxes"  id="surname" /></td>
    </tr>
    <tr>
        <td>First Name</td><td><input type="text" class="inputboxes"  id="firstName" /></td>
    </tr>
    <tr>
        <td>Birthday</td><td><input type="date" class="inputboxes" id="birthday" /></td>
    </tr>
    <tr>
        <td>Phone Number</td><td><input type="text" class="inputboxes" id="phone"></textarea></td>
    </tr>
    <tr>
        <td>Email Address</td><td><input type="text" class="inputboxes"  id="email" /></td>
    </tr>
    <tr>
        <td>Address</td><td><input type="text" class="inputboxes" id="address"/></td>
    </tr>
    <tr>
        <td>Postcode</td><td><input type="text" class="inputboxes"  id="post"  /></td>
    </tr>
    <tr>
        <td>Group</td><td><select class="inputboxes"  id="group"/>
        <option value="Business">Business</option>
        <option value="Educational">Educational</option>
        <option value="Friend">Friend</option>
    </td>
    </tr>
</table>

<br>
<button id="addButton">Add Contact</button>
<button id="delButton">Delete Contacts</button>
</div>
<hr>
<div class="tablediv">
<h2 class="information" align="center">Contacts</h2>
<div  id="parentDiv"></div>
</div>
</body>
</html>

解决方案

首先非常感谢达伦的建议,结果证明是正确的(稍作改动)

我犯的第一个错误是插入 jquery,我有

<script src="jquery-1.8.3.min.js">
   //code
</script>

当我需要

<script src="jquery-1.8.3.min.js"></script>
   <script>
     //code
   </script>

所以这个很小的错误让我暂时退缩了。

其次,我使用了:

 $(document).on('click','.btnForDiv',function(){

为我的 btnForDiv 类按钮调用 Onclick 事件,其余的都是 Darren :)

再次感谢

4

1 回答 1

0

你可以在这里做一些事情。

一个想法是将您生成的 IDdivbuttonID 存储在一个数组中。然后,您可以在此数组中搜索给定buttonID 以找到其对应的div.

例如(未测试...)

     // outside your generatedDiv method
     var myControls = new Array();

     // then inside your generatedDiv method
     var control = new Array();
     control[0] = divId;
     control[1] = buttonId;
     myControls.push(control);

当您单击时,您button可以获取其 ID,然后搜索myControls数组并查找相应的div

您可以在 jQuery 中执行一个函数来处理所有click生成的按钮。

再次(未测试) - 给你所有的按钮一个类,例如btnForDiv

     $(document).ready(function(){

           $(".btnForDiv").click(function(){

              // get the ID of the button
              var id = $(this).prop("id");
              var divId;
              // now find the div Id related to this button
              for (var i = 0, len = myControls.length; i < len; i++){
                if (myControls[i][1] == id){
                   divId = myControls[i][0];
                   break;
                }
              }

              // you now have the div,so toggle it.
              $("#" + divId).toggle();

           });
     });

我不是 100% 确定你的问题是什么,尽管在黑暗中刺伤帮助..

更新

因为您div的 's 是动态生成并添加到 DOM 中的,所以您可能必须使用on而不是click- 这会将click事件绑定到动态元素。

所以试试这个:

$(".btnForDiv").on("click", function(){

      // get the id.... etc...

});

另外,请确保您确实将类添加btnForDiv到动态生成的按钮中

this.firstName + " " + this.surname + "<button style='color: black;' id='" + buttonid +  "b'" + " class='btnForDiv'> Button </button>" +
于 2012-11-30T17:21:16.100 回答