首页 > 解决方案 > javascript/jquery - 如何从重复出现的父类中获取子类名称的变量

问题描述

编辑(到 JSFiddle 的旧链接是错误的):链接到 JSFiddle 示例:https ://jsfiddle.net/uvexys0a/

我正在尝试使用 jQuery 进行编程,因此它包含一个指向工作人员个人资料页面的 HTML 链接,并使用类名环绕整个每个 div staffList。页面路径作为子类存储在每个 div 中,如 JSFiddle 所示。

该代码似乎在某种程度上起作用。两个链接最终都指向 John Smith 的个人资料:

<a href="https://example.com/john-smith">
    <div class="staffList john-smith">
        <p>John Smith</p>
        <p>Co-Founder</p>
    </div>
</a>

<a href="https://example.com/john-smith">
    <div class="staffList jane-smith">
        <p>Jane Smith</p>
        <p>Co-Founder</p>
    </div>
</a>

但是,如果代码运行正常,它会输出如下:

<a href="https://example.com/john-smith">
    <div class="staffList john-smith">
        <p>John Smith</p>
        <p>Co-Founder</p>
    </div>
</a>

<a href="https://example.com/jane-smith">
    <div class="staffList jane-smith">
        <p>Jane Smith</p>
        <p>Co-Founder</p>
    </div>
</a>

您如何编码以便变量staffURL随着每个重复的父 div 与父类staffList和子类对应的工作人员的链接而变化?

标签: javascriptjquery

解决方案


您需要遍历每个staffList项目才能动态设置 URL。

jQuery(function($) {

  /**
   * Loop through each list item
   */
  $('.staffList').each(function() {
    var $listItem = $(this);

    var staffSlug = $listItem
      .attr('class') // Get the value of the class attribute
      .replace('staffList', '') // Remove the common class
      .trim(); // Clear up any pre/appending white space

    // Wrap element in `a` tag
    $listItem.wrap('<a href="https://example.com/' + staffSlug + '"></a>');
  });

});
.staffList {
  border: 1px solid #000;
  margin: 15px;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="warpper">
    <div id="staffSection">

      <div class="staffList john-smith">
        <p>John Smith</p>
        <p>Co-Founder</p>
      </div>

      <div class="staffList jane-smith">
        <p>Jane Smith</p>
        <p>Co-Founder</p>
      </div>

    </div>
  </div>
</div>


推荐阅读