【问题标题】:Merging two unordered lists of first and last names合并两个无序列表的名字和姓氏
【发布时间】:2016-04-08 14:22:22
【问题描述】:

我正在尝试合并两个列表。一个是名字列表,第二个是姓氏列表。我想弄清楚 jQuery 的最佳方法是什么

我有这个:

<ul class="first-names">
    <li>John</li>
    <li>Betty</li>
</ul>

<ul class="last-names">
    <li>Doe</li>
    <li>White</li>
</ul>

我想要这个:

<ul class="full-names">
    <li>John Doe</li>
    <li>Betty White</li>
</ul>

到目前为止,我已经尝试过了,但它甚至还没有接近工作:

$( "ul.last-names li" ).text(function( index ) {
    $('u.first-names li').append(this).text();
});
$("ul.first-names").removeClass("first-names").addClass("full-names");

结果是:

<ul class="full-names">
    <li>John</li>
    <li>Doe</li>
    <li>White</li>
    <li>White</li>
    <li>Betty</li>
    <li>Doe</li>
    <li>White</li>
    <li>White</li>
</ul>

谢谢!

【问题讨论】:

  • 欢迎来到 SO。您需要展示您的尝试。请发布您的 jQuery。
  • 感谢您的提醒!我刚刚编辑以展示我的尴尬尝试。 ;)

标签: jquery html html-lists


【解决方案1】:

假设这两个列表长度相等,您可以使用如下函数循环遍历每个 &lt;ul&gt; 元素并将名称附加到生成的 &lt;ul&gt; 中:

<script>
    $(function(){
        MergeNames();
    });

    function MergeNames(){
      // Assumes that the number of elements are equal
      var firstNames = $('.first-names li');
      var lastNames = $('.last-names li');
      // Ensure they are equal (optional)
      if(firstNames.length == lastNames.length){
        // Loop through and build your new list
        for(var i = 0; i < firstNames.length; i++){
           $('.full-names').append('<li>' + $(firstNames[i]).text() + ' ' + $(lastNames[i]).text() + '</li>');
        }
      }
    }
  </script>

您可以see an example of this in action here 和下面的结果输出:

【讨论】:

    【解决方案2】:

    我建议,假设您只想留下一个全名列表,相关的名字和姓氏是按顺序排列的:

    // caching the relevant last-name <li> elements, and then
    // removing them from the HTML:
    var lastNames = $('.last-names li').remove();
    
    // selecting the <ul> with the class-name of 'first-names',
    // using .toggleClass() to remove the classes that the
    // <ul> currently has ('first-names') and adding those
    // that it does not currently have ('full-names').
    $('ul.first-names').toggleClass('first-names full-names')
    
      // finding the <li> elements in that <ul>:
      .find('li')
    
      // updating the text of those elements, via the anonymous
      // function of the text() method; the first argument ('i')
      // is the index of the current element in the jQuery collection
      // returned by the selector:
      .text(function(i){
    
        // here we trim the text content of the current Node (not
        // a jQuery object) using String.prototype.trim()
        // and concatenating that with a blank space and the
        // <li> of the equal index to the current node (here we
        // use get() to retrieve the DOM node from the cached
        // collection):
        return this.textContent.trim() + ' ' + lastNames.get( i ).textContent.trim();
    });
    

    var lastNames = $('.last-names li').remove();
    
    $('ul.first-names').toggleClass('first-names full-names').find('li').text(function(i) {
      return this.textContent.trim() + ' ' + lastNames.get(i).textContent.trim();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="first-names">
      <li>John</li>
      <li>Betty</li>
    </ul>
    
    <ul class="last-names">
      <li>Doe</li>
      <li>White</li>
    </ul>

    使用纯 JavaScript 也相对简单,虽然比较冗长:

    // caching a reference to the last-names <ul>:
    var lastNamesList = document.querySelector('ul.last-names'),
    
    // caching references to the descendant <li> elements of the
    // last-names <ul>, converting the collection to an Array,
    // using Array.from():
        lastNames = Array.from( lastNamesList.querySelectorAll('li') ),
    
    // caching the first-names <ul>:
        firstNameList = document.querySelector('ul.first-names');
    
    // removing the 'last-names' class from the element:
    firstNameList.classList.remove('last-names');
    
    // adding the 'full-names' class-name:
    firstNameList.classList.add('full-names');
    
    // using querySelectorAll() to find the child <li> nodes of the
    // first-names <ul>, and converting that collection to an Array
    // in order to use the Array.prototype.forEach() method:
    Array.from( firstNameList.querySelectorAll('li') ).forEach(function(li, index) {
      // in the anonymous function:
      // 'li':     a reference to the current <li> element of the
      //           array of nodes over which we're iterating,
      // 'index' : the index of the current array-element within the
      //           array over which we're iterating
    
      // here we update the textContent of the current <li> to a
      // combination of the trimmed current textContent, plus a
      // space plus the trimmed textContent of the <li> of the
      // same index held within the lastNames array:
      li.textContent = li.textContent.trim() + ' ' + lastNames[ index ].textContent.trim();
    });
    
    // here we find the parent of the lastNamesList node, and
    // use the cached reference to remove that Node from the
    // document:
    lastNamesList.parentNode.removeChild(lastNamesList);
    

    var lastNamesList = document.querySelector('ul.last-names'),
      lastNames = Array.from(lastNamesList.querySelectorAll('li')),
      firstNameList = document.querySelector('ul.first-names');
    
    firstNameList.classList.remove('last-names');
    firstNameList.classList.add('full-names');
    
    Array.from(firstNameList.querySelectorAll('li')).forEach(function(li, index) {
      li.textContent = li.textContent.trim() + ' ' + lastNames[index].textContent.trim();
    });
    
    lastNamesList.parentNode.removeChild(lastNamesList);
    <ul class="first-names">
      <li>John</li>
      <li>Betty</li>
    </ul>
    
    <ul class="last-names">
      <li>Doe</li>
      <li>White</li>
    </ul>

    参考资料:

    【讨论】:

    • 很好的详细答案和方法。会退回这个并删除我的。
    【解决方案3】:

    以后,请展示您的尝试,并在适当的情况下进行演示。这是我要做的:

    <script>
    $('#first-names li').each(function() {
        var idx = $(this).index();
        var firstName = $(this).text();
        var lastName = $('#last-names li').eq(idx).text();
    
        $('#full-names').append('<li>' + firstName + ' ' + lastName + '</li>');
    });
    </script>
    

    Demo

    请注意,我已将您的选择器转换为 ID。我觉得这里合适。此外,尚不清楚您是否打算以编程方式创建组合列表,以及它是否应该替换原始列表之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 2017-04-09
      • 2015-03-08
      相关资源
      最近更新 更多