简体   繁体   English

一次仅隐藏/显示一个DIV的功能

[英]Function to hide/show only one DIV at a time

I currently have a JavaScript that is looking at a SharePoint list, and pulling back all of the items that meet the criteria in the REST call. 我目前有一个JavaScript正在查看SharePoint列表,并撤回所有符合REST调用条件的项目。

It currently creates DIVs and appends them to a wrapper DIV. 当前,它创建DIV,并将其附加到包装器DIV。 The intention of the button is to show/hide the sub-DIVs. 该按钮的目的是显示/隐藏子DIV。

Right now, when I click any of the buttons that are produced, it expands all of the hidden divs. 现在,当我单击生成的任何按钮时,它将展开所有隐藏的div。 What I'm trying to accomplish is to be able to click each respective button and have its nested div show/hide. 我要完成的工作是能够单击每个按钮并使其嵌套的div显示/隐藏。

Here is my code: 这是我的代码:

 var listName = "announcement"; var titleField = "Title"; var tipField = "Quote"; var dateFieldFrom = "DateFrom"; var dateFieldTo = "DateTo"; var category = "category"; var noteField = "note"; var query = "/_api/Web/Lists/GetByTitle('" + listName + "')/items?$select=" + titleField + "," + dateFieldTo + "," + dateFieldFrom + "," + category + "," + noteField + "," + tipField; var today = new Date(); var btnClass = "toggle" todayString = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate(); //This is the query filter string where we compare the values in the 2 date fields against the current date query += "&$filter=('" + todayString + "' ge " + dateFieldFrom + " ) and (" + dateFieldTo + " ge '" + todayString + "')";; var call = $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + query, type: "GET", dataType: "json", headers: { Accept: "application/json;odata=verbose" } }); call.done(function(data, textStatus, jqXHR) { var divCount = data.d.results.length; for (var i = 0; i < divCount; i++) { var tip = data.d.results[i][tipField]; //this is where it looks at the quote field to determine what quote to place in the current dynamically created DIV var cat = data.d.results[i][category]; //this is where it looks at the category field to determine what color to style the background of the current dynamically created DIV var message = data.d.results[i][noteField]; var ID = "NewDiv-" + i var PID = "P-" + i var BID = "btn-" + i // Create Message DIV var element = document.createElement("div"); //This is the creation of the dynamic DIV element.id = ID //This is assigning a DIV an ID element.appendChild(document.createTextNode(tip)); // Create Inner message DIV var innerDiv = document.createElement("div"); // Create a <div> element//New Code innerDiv.id = PID innerDiv.appendChild(document.createTextNode(message)); // Create button to show/hide the div var btn = document.createElement("BUTTON"); btn.id = BID btn.appendChild(document.createTextNode("show/hide message below")); btn.className = btnClass // Append Inner DIVs document.getElementById('wrapper').appendChild(element); //This is the parent DIV element that all newly created DIVs get created into document.getElementById(ID).appendChild(btn); // Append the button to the newly created DIV document.getElementById(ID).appendChild(innerDiv); //This is the message that appears after the newly created DIVs if (cat == 'Information') { document.getElementById(ID).style.backgroundColor = '#d9edf7'; //Blue Color document.getElementById(PID).style.backgroundColor = '#d9edf7'; //Blue Color document.getElementById(PID).style.margin = '3px'; document.getElementById(BID).style.backgroundColor = '#d9edf7'; document.getElementById(BID).style.border = 'none'; innerDiv.className = "alert alert-info" element.className = "alert alert-info" } if (cat == 'Warning') { document.getElementById(ID).style.backgroundColor = '#fcf8e3'; //Orange Color document.getElementById(PID).style.backgroundColor = '#fcf8e3'; //Orange Color document.getElementById(PID).style.margin = '3px'; document.getElementById(BID).style.backgroundColor = '#fcf8e3'; document.getElementById(BID).style.border = 'none'; innerDiv.className = "alert alert-warning" element.className = "alert alert-warning" } if (cat == 'Critical') { document.getElementById(ID).style.backgroundColor = '#f2dede'; //Red Color document.getElementById(PID).style.backgroundColor = '#f2dede'; //Red Color document.getElementById(PID).style.margin = '3px'; document.getElementById(BID).style.backgroundColor = '#f2dede'; document.getElementById(BID).style.border = 'none'; innerDiv.className = "alert alert-danger" element.className = "alert alert-danger" } } // The below variables and for loop ensure that all sub messages are initially hidden, until the show/hide button is clicked var curDiv var curID for (var i = 0; i < divCount; i++) { curID = "P-" + i curDiv = document.getElementById(curID) curDiv.style.display = 'none'; } // The function below is to assign an event to the button to show/hide the sub message var f = function(a) { var cDiv for (var z = 0; z < divCount; z++) { cDiv = "P-" + z var div = document.getElementById(cDiv); if (div.style.display !== 'none') { div.style.display = 'none'; } else { div.style.display = 'block'; } } return false; } var elems = document.getElementsByClassName("toggle"); var idx for (var i = 0, len = elems.length; i < len; i++) { elems[i].onclick = f; } }); 
 <div id="wrapper" class="header"> </div> 

You can replace all of this - which loops over all divs 您可以替换所有这些-遍历所有div

// The function below is to assign an event to the button to show/hide the sub message
  var f = function(a) {
    var cDiv
    for (var z = 0; z < divCount; z++) {
      cDiv = "P-" + z
      var div = document.getElementById(cDiv);
      if (div.style.display !== 'none') {
        div.style.display = 'none';
      } else {
        div.style.display = 'block';
      }
    }
    return false;
  }
  var elems = document.getElementsByClassName("toggle");
  var idx
  for (var i = 0, len = elems.length; i < len; i++) {
    elems[i].onclick = f;
  }

with this, it delegates the click on the button in the wrapper and toggles the next object after the button 这样,它委派了包装器中按钮的单击,并在按钮之后切换下一个对象

$('#wrapper').on("click",".toggle",function(e) { // notice the delegation
  e.preventDefault(); // in case you forget type="button"
  $(this).next().toggle();
});

Like this: 像这样:

 $(function() { $('#wrapper').on("click", ".toggle", function(e) { e.preventDefault(); $(this).next().toggle(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="wrapper"> <div id="NewDiv-0" class="alert alert-info" style="background-color: rgb(217, 237, 247);">Debbie Teng joins PD Tax!******** <button id="btn-0" class="toggle" style="background-color: rgb(217, 237, 247); border: none;">show/hide message below</button> <div id="P-0" class="alert alert-info" style="background-color: rgb(217, 237, 247); margin: 3px; display: none;">yadayada1​</div> </div> </div> 

You're assigning all of your buttons the same onclick function event handler, and that function loops through all the divs and shows them or hides them. 您为所有按钮分配了相同的onclick函数事件处理程序,该函数循环遍历所有div并显示或隐藏它们。

An alternative approach would be to have the event handler toggle only the specific div that's associated with the button. 一种替代方法是让事件处理程序仅切换与按钮关联的特定div。

When you first create the button, you can assign an event handler to it immediately and pass in a reference to the div you want to hide: 首次创建按钮时,可以立即为其分配事件处理程序,然后将引用传递给要隐藏的div:

var innerDiv = document.createElement("div");
innerDiv.id = PID
innerDiv.appendChild(document.createTextNode(message));
var btn = document.createElement("BUTTON");
// Immediately-invoked function expression to attach event handler to inner div:
(function(d){
    btn.onclick = function(){ f(d); };
})(innerDiv);

Then just update your f function to accept as a parameter the div you want to toggle. 然后只需更新您的f函数,以接受要切换的div作为参数即可。

// The function below is to assign an event to the button to show/hide the sub message
function f(div){
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    } else {
        div.style.display = 'block';
    }
    return false;
}

You can then remove the last few lines of code where you're assigning the buttons to the elems collection and looping through it to attach an onclick function. 然后,您可以删除将代码分配给elems集合的最后几行代码,并循环遍历该代码以附加onclick函数。

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

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