此问题需要一些背景信息才能理解。 我有一堆关于濒危语言的故事。每个故事都分为几行。默认情况下,页面仅显示英文全文和另一种语言的全文。每行都有一个小的切换按钮,使他们可以打开逐词翻译。
我在顶部还有一个“全部切换”按钮,用于打开和关闭所有逐字翻译。它适用于少于20行的故事,但是我们有一些故事具有100行以上的故事,在这些页面上,“切换全部按钮”需要30秒钟以上的时间才能工作。
我有点像是一个有很多知识的中级程序员,我想知道是否有一种方法可以重写它以使其更快/更有效。
这是故事中一个示例行后面的HTML
<div class="row">
<div class="col-lg-2 col-xs-12">
<audio id="line1audio" src="sounds/GivingaShottoaSheep2/1_that_guy_there_EC.mp3" preload="auto"></audio>
<button class="btn btn-light" onclick="document.getElementById('line1audio').play();"><i class="fas fa-volume-up"></i></button> <button class="btn btn-info" type="button" data-toggle="collapse" data-target=".multi-collapse1" aria-expanded="false" aria-controls="line1gloss line1Translation">Gloss</button>
</div>
<div class="col-lg-5 col-xs-12">
<p class="mainPomo">bo:w jaʔnamo:w</p>
</div>
<div class="col-lg-5 col-xs-12 collapse multi-collapse1 show translation" id="line1Translation">
<p>That guy there,</p>
</div>
</div>
<div class="row collapse multi-collapse1 gloss" id="line1gloss">
<div class="col-lg-2 col-xs-0"></div>
<div class="col-lg-10 col-xs-12">
<dl>
<div class="word">
<dt>bo:w</dt>
<dd>here</dd>
</div>
<div class="word">
<dt>jaʔ</dt>
<dd>person</dd>
</div>
<div class="word">
<dt>-nam</dt>
<dd>-the</dd>
</div>
<div class="word">
<dt>-mo:w</dt>
<dd>-he</dd>
</div>
</dl>
<br style="clear:both;"/>
<p class="mainEnglish">That guy there,</p>
<br/>
</div>
</div>
以下是启用“切换所有按钮”的代码
// this script is the mechanism behind the button that allows you to toggle all of the glosses at once
//if buttonPresses is even, we open all of the glosses. If it is odd, we close them all.
var buttonPresses = 1;
function toggleAllGlosses(idAddOn){
// build some IDs to getElementsBy
var toggleAllButtonId = "toggleAllButton";
var glossId = "gloss";
var translationId = "translation";
// check to see if it is the main story, in which case we don't do anything. If idAddOn is not blank, this
// must be one of the other story versions, and we must add idAddOn to these three variables
if(idAddOn != undefined){
toggleAllButtonId += idAddOn;
glossId += idAddOn;
translationId += idAddOn;
}
// get the button
var toggleAllButton = document.getElementById(toggleAllButtonId);
// get all of the glosses
var glosses = document.getElementsByClassName(glossId);
var translations = document.getElementsByClassName(translationId);
// how the toggle all button actually works
// increase buttonPresses by one
buttonPresses++;
// if buttonPresses is even...
if(buttonPresses%2 == 0){
// show each gloss and hide each translation.
for(var i=0; i<glosses.length;i++){
$(glosses[i]).collapse("show");
$(translations[i]).collapse("hide");
}
}
// if buttonPresses is odd...
else{
// hide each gloss and show each translation.
for(var j=0; j<glosses.length;j++){
$(glosses[j]).collapse("hide");
$(translations[j]).collapse("show");
};
};
};