【问题标题】:Targeting elements without access to html无法访问 html 的目标元素
【发布时间】:2016-03-08 11:11:27
【问题描述】:

我无权访问本文档中的 html,并且我尝试选择的元素具有与另一个元素共享的 ID(优惠券)(选择其中一个元素都可以,因为它们是相同的)。所以我在徘徊,是否有人能告诉我如何在不使用 ID 作为钩子的情况下选择其中之一。

<div class="buttons">

   <div class="discount-module">
            <div id="coupon" class="content" style="display: none;">
              Enter your coupon code code here:&nbsp;
              <input type="text" name="coupon" value="">
              &nbsp;<a id="button-coupon" class="button"><span>Apply coupon</span></a>
            </div>
                                      <div id="vc-messages"></div>
          <div>
            <table class="radio">
                                <tbody><tr class="highlight">
                <td>                      <input type="radio" name="next" value="coupon" id="use_coupon">
                  </td>
                <td><label for="use_coupon">Use coupon Code</label></td>
              </tr>
                                                                 </tbody></table>
          </div>

          <div class="discount-module">
            <div id="coupon" class="content" style="display: none;">
              Enter your coupon code code here:&nbsp;
              <input type="text" name="coupon" value="">
              &nbsp;<a id="button-coupon" class="button"><span>Apply coupon</span></a>
            </div>
            <div id="voucher" class="content" style="display: none;">
              Enter your voucher code code here:&nbsp;
              <input type="text" name="voucher" value="">
              &nbsp;<a id="button-voucher" class="button"><span>Apply voucher</span></a>
            </div>
            <div id="reward" class="content" style="display: none;">
              Points to use (Max 0):&nbsp;
              <input type="text" name="reward" value="">
              &nbsp;<a id="button-reward" class="button"><span>Apply reward</span></a>
            </div>
          </div>

【问题讨论】:

  • 取决于可以依赖结构的哪些限制——像.discount-module &gt; div:first-child 这样简单的东西可能已经起作用了。
  • @CBroe 除非我误解了这个问题,否则我认为 OP 只想选择其中一个,而不是两个。
  • @James dunno ... “选择任何一个元素都可以”“如何选择其中一个” - 可能意味着任何一个。
  • 你不能在一个页面上多次使用 ID ......这是你的基本问题。
  • 是的,我只想选择一个

标签: html css css-selectors


【解决方案1】:

在 HTML 中确实不应该有重复的 ID,因为它是无效的,所以我会尽可能避免使用 ID 进行选择。但是,由于在此特定情况下您似乎无法做到,因此您可以采取以下一种方法。

第一张优惠券

.discount-module:first-of-type #coupon {
}

第二张优惠券

.discount-module:nth-of-type(2) #coupon {
}

如果您保证#coupon div 将成为.discount-module div 中的第一个div 元素。你可以使用类似的东西

.discount-module:first-of-type > div:first-of-type

【讨论】:

  • .discount-module:first-of-type > div:first-of-type 有效! :D ty ty ty
  • .discount-module:first-child > div:first-child 也有效:D
猜你喜欢
  • 2021-04-23
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2020-01-26
相关资源
最近更新 更多