首页 > 解决方案 > jquery嵌套时找不到id,但不嵌套时找到

问题描述

我有一段这样的 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>

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

标签: javascriptjqueryhtmljquery-selectors

解决方案


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


推荐阅读