【问题标题】:Can I use getElementById to select and hide content that does not have the id specified?我可以使用 getElementById 来选择和隐藏没有指定 id 的内容吗?
【发布时间】:2017-11-08 19:36:45
【问题描述】:

比如我有这个功能。

function showprintdiv() {
    var x = document.getElementById('post-Print ');
    if (!x.style.display || x.style.display == 'block') {
        x.style.display = 'none';
    } else {
        x.style.display = 'block';
}

我有这个功能 7 次,其中 8 个部分具有通过

生成的 ID
<div id="post-<?php
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            echo $tag->name . ' '; 
        }
    }
?>" class="col-md-4 no-pad containerhover">

目前当我点击一个按钮时,它会隐藏或显示post-Print的内容

我希望它隐藏/显示我拥有的其他 7 个部分的内容,所以 post-Print 一直都在那里。

我认为应该有某种方法来隐藏每个带有类的 DIV,除非它们具有指定的 ID。

【问题讨论】:

标签: javascript php


【解决方案1】:

首先,HTML 的id 属性应该是not contain any spaces,因此您需要为此调整您的PHP 代码。在以下操作之前必须这样做:

专注于您的问题:如果您想获取所有 post- 元素,除了一个特定元素 post-Print,然后使用 querySelectorAll 和智能 CSS 选择器 [id^=post-]:not(#post-Print) .

这是一个演示:

function showprintdiv() {
    // Iterate over all elements that have an id that starts with "post-",
    // except the one you want to keep visible:
    var elems = document.querySelectorAll('[id^=post-]:not(#post-Print)');
    Array.from(elems, function (x) {
        if (x.id == 'post-Print') return; // don't touch this one.
        x.style.display = (!x.style.display || x.style.display == 'block')
            ? 'none' : 'block';
    });
}

// Demo: toggle visibility every half second:
setInterval(showprintdiv,  500);
<div id="post-Print" class="col-md-4 no-pad containerhover">post-Print</div>
<div id="post-1"     class="col-md-4 no-pad containerhover">post-1</div>
<div id="post-2"     class="col-md-4 no-pad containerhover">post-2</div>
<div id="post-3"     class="col-md-4 no-pad containerhover">post-3</div>

【讨论】:

  • 您能给我一些反馈吗?这回答了你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 2018-01-14
  • 2021-10-16
  • 2020-01-25
相关资源
最近更新 更多