简体   繁体   English

如何将展开全部按钮添加到 javascript/HTML 项目

[英]How to Add an Expand All button to a javascript/HTML project

I currently have a page that has content that expands when you click on a term, but as soon as you click on a new term the old one closes and the new one expands.我目前有一个页面,当您单击一个术语时,该页面的内容会扩展,但是一旦您单击一个新术语,旧术语就会关闭,而新术语会展开。 The terms are loaded in from a google sheet onto the page.这些条款是从谷歌表格加载到页面上的。 This is on a HTML page but the javascript code to do the work is the following:这是在 HTML 页面上,但执行该工作的 javascript 代码如下:

// Address of the Google Sheets Database
var public_spreadsheet_url = 'sheet link here';

// Column Names from Google Sheets Database
let questionsColumn = "Question";
let answersColumn = "Answer";

window.addEventListener('DOMContentLoaded', init)   // Calls method init when Sheets has loaded

function init() {
Tabletop.init( { key: public_spreadsheet_url,
                 callback: showInfo,
                 simpleSheet: true } );
}

var unhiddenAnswer = "";

// Method that gets called when data has been pulled from Google Sheets
function showInfo(data) {
    var editButton = '<center><a style="border-bottom: none" href="' + public_spreadsheet_url + '"><button class="button admin">Edit</button></a></center>';

    // Injects the built HTML code into the div Dynamic
    document.getElementById("dynamic").innerHTML = buildFAQTable(data) + editButton;
}

// Builds the HTML Table code from the Database Data
function buildFAQTable(data) {
    var index = 0;
    var content = '<h2>Title Here</h2><div style="padding:0px 5%">';
    data.forEach(form => {
        content += '<h1 class="faq_question" onClick="unhideAnswer(' + index + ')">' + data[index][questionsColumn] + '</h1>';
        content += '<p id="answer' + index + '" class="hideAnswer">' + data[index][answersColumn] + '</p>';
        index++;
    });
  // Extends body to accomdate for tall footer on very small devices (e.g. iPhone 5/5S/SE)
  content += "<br></br><br></br>";
    return content;
}

// When a FAQ Question gets clicked on, this method will hide the currently displaying answer (if any), and
// Unhide the answer corresponding to the clicked on answer.
// If the currently displaying answer is the same as the answer corresponding to the clicked on question,
// it will be hidden and no new answer will be unhidden
function unhideAnswer(number) {
    var answerID = "answer" + number;
    if (answerID != unhiddenAnswer) {
        document.getElementById(answerID).classList.remove("hideAnswer");
    }
    if (unhiddenAnswer != "")
        document.getElementById(unhiddenAnswer).classList.add("hideAnswer");
    if (unhiddenAnswer == answerID)
        unhiddenAnswer = ""
    else
        unhiddenAnswer = answerID;
}

I want to now add an expand all/ collapse all button to give the user the option to open and view all the terms at one if needed.我现在想添加一个全部展开/全部折叠按钮,让用户可以选择在需要时一次性打开和查看所有条款。 However, if not using the expand all button, the regular open and close functionality above should be used.但是,如果不使用全部展开按钮,则应使用上面的常规打开和关闭功能。 I am new to javascript and am at a loss on the best way to implement this.我是 javascript 的新手,不知道实现这一点的最佳方法。 Any help would be appreciated.任何帮助,将不胜感激。

add a answer class to every answer, then you can loop through all of them with this query selector将答案 class 添加到每个答案,然后您可以使用此查询选择器遍历所有答案

// in your buildFAQTable fucntion
content += '<p id="answer' + index + '" class="hideAnswer answer">' + data[index][answersColumn] + '</p>';


document.querySelectorAll('.answer').forEach(answer => {
  // you can use toggle, add or remove to change the appearance of the answer
  answer.classList.toggle('hideAnswer')
})

i would also recomend you to check out some of the newer javascript features like string interpolation and avoid using var, but it is not so important if you are just starting out.我还建议您查看一些较新的 javascript 功能,例如字符串插值并避免使用 var,但如果您刚刚开始,这并不是那么重要。

(i also refactored some of your code, this might make it a bit more readable) (我还重构了你的一些代码,这可能使它更具可读性)

// Address of the Google Sheets Database
const public_spreadsheet_url = 'sheet link here';

// Column Names from Google Sheets Database
const questionsColumn = "Question";
const answersColumn = "Answer";

function toggleAnswer(num) {
        const answer = document.getElementById(`answer${num}`);
        answer.classList.toggle('hideAnswer');
}

function hideAll() {
        document.querySelectorAll('answer').forEach(answer => {
                answer.classList.add('hideAnswer');
        })
}

function showAll() {
        document.querySelectorAll('answer').forEach(answer => {
                answer.classList.remove('hideAnswer');
        })
}

function buildFAQTable(data) {
        let index = 0;
        let content = '<h2>Title Here</h2><div style="padding:0px 5%">';

        for (i in data) {
                content += `<h1 class="faq_question" onClick="unhideAnswer(${i})">${data[i][questionsColumn]}</h1>`;
                content += `<p id="answer${i}" class="hideAnswer answer">${data[i][answersColumn]}</p>`;
        }

        content += "<br></br><br></br>";
        return content;
}

function showInfo(data) {
        const editButton = `<center><a style="border-bottom: none" href="${public_spreadsheet_url}"><button class="button admin">Edit</button></a></center>`;

        document.getElementById("dynamic").innerHTML = buildFAQTable(data) + editButton;
}

window.addEventListener('DOMContentLoaded', () => {
    Tabletop.init({
        key: public_spreadsheet_url,
        callback: showInfo,
        simpleSheet: true
    });
}, { once: true })

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

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