生成具有用于切换隐藏/显示的独特按钮的Div

时间:2012-11-30 16:41:02

标签: javascript html button toggle

我正在制作一个通讯录,并且每个新条目都会生成一个包含所有信息的Div。我已经为每个生成的div提供了一个唯一的ID,并且每个按钮都生成了一个唯一的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>

解决方案

首先,非常感谢Darren的建议,结果证明是现场(稍有改动)

我做的第一个错误是插入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:)

再次感谢

1 个答案:

答案 0 :(得分:0)

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

一个想法是将生成的divbutton ID存储在数组中。然后,您可以在此数组中搜索给定的button ID,以查找其对应的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();

           });
     });

我不是百分百肯定你的问题是什么,虽然在黑暗中刺了一下帮助......

<强>更新

由于您的div已生成并动态添加到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>" +