javascript / jquery-如何从父类的重复出现中获取子类名称的变量

时间:2019-03-06 15:50:31

标签: javascript jquery

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

我正在尝试使用jQuery进行编程,因此它包装了指向工作人员资料页面的HTML链接,并用类名<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> 环绕了每个div。页面的路径在每个div中作为子类存储,如JSFiddle所示。

代码似乎起作用了。这两个链接最终都转到了约翰·史密斯的个人资料:

<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

您如何编码,以便变量staffList在父类为{{1}}的每个重复的父div中都发生变化,子类为相应的工作人员链接?

2 个答案:

答案 0 :(得分:1)

您将链接基于第二类名称,但是在第二个StaffList中,您再次说了约翰·史密斯,因此每个链接两次都获得了约翰·史密斯。您可以将其更改为简史密斯,然后遍历每个项目以获得所需的内容。试试这个:

jQuery(function($){
  var staffList = $(".staffList");
  
  $.each(staffList, function(i) {
    var staffURL = $(this).attr('class').split(' ')[1];
    $(staffList[i]).wrap("<a href='https://example.com/"+staffURL+"/'></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>

jsfiddle:https://jsfiddle.net/7nxbu1t5/2/

答案 1 :(得分:1)

您需要遍历每个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>