繁体   English   中英

在不使用uniq ID的情况下影响所选div的按钮

[英]Button affecting selected div without using uniq ID

如何为按钮创建脚本,使其仅在不使用ID和.getElemetByID方法的情况下在此按钮所在的块上起作用? 这是一个示例,其中我仅对一个按钮使用ID,但我想使所有按钮扩展其父块。

 function toggle() { var tBlock = document.getElementById("textblock"); var tText = document.getElementById("text"); if (tBlock.style.height === "100px" && tText.style.height === "60px") { tBlock.style.height = "auto"; tText.style.height = "auto"; } else { tBlock.style.height = "100px"; tText.style.height = "60px"; } } 
 .docText { height: 100px; width: 100px; background: green; margin-bottom: 5px; } .docTextContent { height: 60px; width: 100px; overflow: hidden; } 
 <div class="docText" id="textblock"> <div class="docTextContent" id="text"> TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText </div> <button class="toggle_btn" onclick="toggle()">Show</button> </div> <div class="docText"> <div class="docTextContent"> TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText </div> <button class="toggle_btn">Show</button> </div> <div class="docText"> <div class="docTextContent"> TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText </div> <button class="toggle_btn">Show</button> </div> 

尝试使用以下代码。

<button onclick=“function()”></button>

您可以通过使用类名称检索所有切换按钮,然后在绑定单击处理程序时在它们之间循环来完成此操作。 这是一个工作示例:

 // GET ALL TOGGLES var toggles = document.getElementsByClassName("toggle_btn"); // LOOP THROUGH EACH TOGGLE AND APPLY AN EVENT LISTENER for (var i = 0; i < toggles.length; i++) { toggles[i].addEventListener("click", function(e) { e.preventDefault(); // GET .docTextContent ELEMENT var tBlock = this.parentElement.children[0]; // IF .docTextContent IS "CLOSED" if (tBlock.style.height === "60px" || tBlock.style.height === "") { tBlock.style.height = "auto"; } // .docTextContent IS "OPEN" else { tBlock.style.height = "60px"; } }); } 
 .docText { width: 100px; background: green; margin-bottom: 5px; } .docTextContent { height: 60px; width: 100px; overflow: hidden; } 
 <div class="docText" id="textblock"> <div class="docTextContent" id="text"> TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText </div> <button class="toggle_btn">Show</button> </div> <div class="docText"> <div class="docTextContent"> TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText </div> <button class="toggle_btn">Show</button> </div> <div class="docText"> <div class="docTextContent"> TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText </div> <button class="toggle_btn">Show</button> </div> 

暂无
暂无

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

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