【问题标题】:jQuery select next div elementjQuery选择下一个div元素
【发布时间】:2020-05-03 19:14:49
【问题描述】:

结构:

<div id="XY">
    <p>Test</p>
    <ul>
       <li>Test<a class="link"></a></li>
    </ul>
</div>

我的目标是获取 div 的 ID 并将其插入到“链接”项的链接中。

    <script>
    $(document).ready(function() {
        $(".link").attr("href", "open_" + $(this).parent("div").attr('id'));
    });
    </script>

【问题讨论】:

    标签: jquery select parent next


    【解决方案1】:

    你可以这样做:

    $(document).ready(function() {
      $(".link").attr("href", "open_" + $(".link").closest("div").attr('id'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="XY">
        <p>Test</p>
        <ul>
           <li>Test<a class="link"></a></li>
        </ul>
    </div>

    如果您有更多的链接适用于此,只需使用each():

    $(document).ready(function() {
       $(".link").each(function() {
          $(this).attr("href", "open_" + $(this).closest("div").attr('id'));
       });
    });
    

    【讨论】:

    • var 计数器 = 0; $(".ruleLink").each(function() { $(this).attr("href", "#open_" + $(this).closest("div").attr("id") + " " + counter); $(this).next("blockquote").attr("id", "open" + $(this).closest("div").attr("id ") + "_" + 计数器); $(this).next("blockquote").html("" + $(this).text() + "
      " + $(this).next("blockquote").html()) $(this).next("blockquote").hide(); counter++; });它适用于

      但不适用于普通

      。想法?
    • @FelixS.我认为

      不能包含

      元素,因此它不起作用。如果您使用 DOM 检查器检查jsfiddle.net/o3hLqd86,您会注意到块引用不像它所写的那样位于

      元素内,而是位于

      下方,因为浏览器倾向于纠正无效的 HTML。根据developer.mozilla.org/en-US/docs/Web/HTML/Element/p,

      只能包含短语内容,而 blockquote 不属于该内容。

    猜你喜欢
    • 2021-10-03
    • 2010-12-16
    • 1970-01-01
    • 2011-11-29
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    相关资源
    最近更新 更多