jquery - append Icons generated by for loop into l

2020-07-14 05:27发布

问题:

I would be very grateful for some guidance or even a solution!

From an array of class names, I'm generating icon sets using a for loop:

// icon array
var iconsArray = ['fa-search','fa-toggle-up','fa-link']; 
var iconsArrayLength = iconsArray.length;

    // loop through array
    for (var i = 0; i < iconsArrayLength; i++) {

        // result
        console.log('<i class="fa' + ' ' + iconsArray[i] + '"></i>');

    }

I also have a navigation element. The list has the same number of items with an ID:

<nav>

    <ul id="nav">

        <li><a href="">link 1</a></li>
        <li><a href="">link 2</a></li>
        <li><a href="">link 3</a></li>

    </ul>

</nav>

Q. How do I append / prepend the returned icon sets to the correct nav item?

To be clear, the first array value is intended for the first navigation item and so on.

I'm sure there's something out there to answer this question, but the mighty G just doesn't seem to want to serve it up to me!

Thanks in advance.

In response to comment...

The resulting list would look like this:

<nav>

    <ul id="nav">

        <li><a href=""><i class="fa fa-search"></i>link 1</a></li>
        <li><a href=""><i class="fa fa-toggle-up"></i>link 2</a></li>
        <li><a href=""><i class="fa fa-link"></i>link 3</a></li>

    </ul>

</nav>

回答1:

You don't even need the for loop

$('#nav li').each(function(i) {
    $(this).append('<i class="fa' + ' ' + iconsArray[i] + '"></i>')
})


回答2:

You can do it like this:

var iconsArray = ['fa-search', 'fa-toggle-up', 'fa-link'];

$('#nav li a').append(function(i) {
    return '<i class="fa ' + iconsArray[i] + '"></i>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link data-require="font-awesome@*" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />

<nav>
  <ul id="nav">
    <li><a href=""></a></li>
    <li><a href=""></a></li>
    <li><a href=""></a></li>
  </ul>
</nav>



回答3:

I'd suggest, to add the <i> with the relevant class:

// iterates over each of the found <a> elements:
$('li a').append(function (i) {
    // i: the index of the current element/node in
    // the collection returned by the selector:

    // returning the created <i> element to the append method:
    return $('<i>', {
        // setting the className of the created element:
        'class' : 'fa ' + iconsArray[i]
    });
});

var iconsArray = ['fa-search', 'fa-toggle-up', 'fa-link'];
$('#nav li a').append(function(i) {
  return $('<i>', {
    'class': 'fa ' + iconsArray[i]
  });
});
<link data-require="font-awesome@*" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>

  <ul id="nav">

    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>

  </ul>

</nav>

Or, with plain JavaScript:

var iconsArray = ['fa-search', 'fa-toggle-up', 'fa-link'],
    // using CSS notation with document.querySelectorAll() to
    // retrieve the relevant <a> elements:
    navAnchors = document.querySelectorAll('#nav li a'),
    // using Array.prototype.slice() (with Function.prototype.call())
    // to convert the NodeList to an array:
    navAnchorsArray = Array.prototype.slice.call(navAnchors, 0),
    // creating an <i> element:
    iElem = document.createElement('i'),
    // an empty variable for use within the loop (later):
    clone;

// all created <li> elements need the 'fa' class for
// font-awesome, so we add that here (once, for all),
// using the HTMLElement.classList API:
iElem.classList.add('fa');

// iterating over each of the <a> elements held in the array:
navAnchorsArray.forEach(function (anchor, index) {
  // cloning the created <i> element (to avoid calling
  // document.createElement() multiple times):
  clone = iElem.cloneNode();

  // adding the class-name from the iconsArray:
  clone.classList.add(iconsArray[index]);

  // appending the cloned/created <i> to the <a>:
  anchor.appendChild(clone);
});

var iconsArray = ['fa-search', 'fa-toggle-up', 'fa-link'],
    navAnchors = document.querySelectorAll('#nav li a'),
    navAnchorsArray = Array.prototype.slice.call(navAnchors, 0),
    iElem = document.createElement('i'),
    clone;

iElem.classList.add('fa');

navAnchorsArray.forEach(function (anchor, index) {
  clone = iElem.cloneNode();
  clone.classList.add(iconsArray[index]);
  anchor.appendChild(clone);
});
<link data-require="font-awesome@*" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>

  <ul id="nav">

    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>
    <li>
      <a href=""></a>
    </li>

  </ul>

</nav>

References:

  • JavaScript:
    • Array.prototype.forEach().
    • Array.prototype.slice().
    • document.createElement().
    • document.querySelectorAll().
    • Element.classList.
    • Function.prototype.call().
    • Node.appendChild().
  • jQuery:
    • append().


回答4:

if you would like to have it just in javascript, you can try something like this:

var iconsArray = ['fa-search','fa-toggle-up','fa-link']; 
var iconsArrayLength = iconsArray.length;

// loop through array
for (var i = 0; i < iconsArrayLength; i++) {

/* nav item selector */
var navItem = document.querySelectorAll("#nav li a")[i];
/* creates <i> icon element */
var icon = document.createElement("i");
/* gives classes .fa and .fa-* to the icon element */
icon.className = "fa " + iconsArray[i];
/* add icon to the item in navigation */
navItem.appendChild(icon);

// result
console.log('<i class="fa' + ' ' + iconsArray[i] + '"></i>');

}