【问题标题】:Hide button if text is empty on particular page structure如果特定页面结构上的文本为空,则隐藏按钮
【发布时间】:2020-11-10 15:15:26
【问题描述】:

我有一个这样结构的页面

    <div id=0>
    ...
       <textarea id=sometext></textarea>
       ...
          <button class="coolbutton"></button>
       ...
    ...
    </div>
    <div id=1>
    ...
       <textarea id=sometext></textarea>
       ...
          <button class="coolbutton"></button>
       ...
    ...
    </div>
    <div id=2>
    ...
       <textarea id=sometext></textarea>
       ...
          <button class="coolbutton"></button>
       ...
    ...
    </div>

当此 div 中的 textarea 为空时,我只需要在第一个 div (id=0) 中隐藏按钮。请注意,只有 div id 不同。 textarea 的 ID 相同。其他 div 中的按钮无需隐藏。
请提供使用 js 或 asp.net mvc 工具的解决方案。有什么不清楚的可以问我。

【问题讨论】:

  • 1.你所有的textareas 都有相同的id,这是错误的。 ids 是独一无二的。 2. 将classNamestyle 添加到隐藏它的第一个button。然后将event listener 添加到您的第一个textarea,这样当value 更改时,它可以取消隐藏/重新隐藏按钮。
  • @RyanWilson 这些 div 是使用循环创建的,因此我不能仅将事件添加到第一个文本区域。因此,我想我可以在所有 textareas 上创建事件侦听器并以某种方式传递 div id,以便我可以在函数中检查它以仅隐藏第一个按钮。但仍然不是我猜的最佳解决方案......
  • '这些 div 是使用循环创建的,所以我不能只将事件添加到第一个 textarea' 当然可以:.commonDivClass:first,或者在纯 CSS 中:stackoverflow.com/a/8539107/519413

标签: javascript jquery asp.net-mvc


【解决方案1】:

请参阅下面的解决方案。由于所有按钮都具有相同的 id,因此您可以使用 childNodes 定位第一个 div 中的空白文本区域。

如果div1 中的第一个textarea 为空,则隐藏其第二个孩子button

代码sn-p有cmets来解释。

//Declare div one using childNodes
  var div1 = document.getElementById("0").childNodes;
  
  //Target second child of div using index [1]
  //The second child of the first div is the empty text area
  if (div1[1].innerHTML === "") {
  //If the text area is empty then hide the button
  div1[3].style.display = "none";
  }
<div id="0">
       <textarea id="sometext"></textarea>
          <button class="coolbutton">Click</button>
    </div>
    <div id="1">
       <textarea id="sometext">some text</textarea>
          <button class="coolbutton">Click</button>
    </div>
    <div id="2">
       <textarea id="sometext">some text</textarea>
          <button class="coolbutton">Click</button>
    </div>

【讨论】:

  • 看起来你的解决方案在 sn-p 中不起作用,但我还是明白了
  • 查看编辑,我使用了您的原始代码,看起来 id 周围没有引号。 - 至于您的问题,您说您想使用id=0 定位div,如果textarea 没有任何文本,则应隐藏按钮。 - 上面的解决方案解决了这个问题。该按钮已隐藏,因为第一个 textarea 中没有任何文本
  • 另外,如果这有助于或解决了您的问题,请点赞或标记正确✔️ - 谢谢!
猜你喜欢
  • 2020-11-06
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多