【问题标题】:jquery cannot find id when nested, but finds it when not nestedjquery嵌套时找不到id,但不嵌套时找到
【发布时间】:2020-07-11 09:58:08
【问题描述】:

我有一段这样的 HTML:

  <body>
    <div id="main" class="popup">
      <h1> Webpage chatter </h1>
      <button id="signOut">Sign Out</button>
      <div id="welcome-section">
        <div id="invalid-error-msg" class="invalid-input-text">
        </div>
      </div>
  ...

还有一个修改 id=invalid-error-msg 元素的 jquery 脚本:

$("#invalid-error-msg").append("<p>Too short. Display name must be 6 or more characters.</p>");

jquery 没有找到 invalid-error-msg id,但是如果我像下面那样取消嵌套该 div,它会找到它并毫无问题地修改它。

  <body>
    <!-- show a text box, a list of persons in chat, chat box, header title -->
    <div id="main" class="popup">
      <h1> Webpage chatter </h1>
      <button id="signOut">Sign Out</button>
      <div id="welcome-section">
      </div>
      <div id="invalid-error-msg" class="invalid-input-text">
      </div>

为什么会这样?这是正常行为吗?

【问题讨论】:

  • 适用于#welcome-section 的 CSS 是否可以隐藏它或其子项?
  • @oflahero 那会怎样?
  • 当您执行console.log($("#invalid-error-msg")) 时,在这两种情况下您会得到什么?
  • 如果您将一百个

    标头附加到#invalid-error-msg Anurag,如果它有一个祖先是 display: none;,比如说。

  • 您确定没有找到它吗?检查 DOM 检查器,看看它是否正常工作。

标签: javascript jquery html jquery-selectors


【解决方案1】:

只要元素存在于渲染的 DOM 中,jQuery 总会找到它。因此,您可能需要检查 id="welcome-section" (这是包装器/父级)CSS。它一定是被隐藏或不显示的。

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 2016-08-24
    • 1970-01-01
    • 2021-10-01
    • 2016-02-21
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多