如何使用JQuery替换的所有元素?

时间:2021-10-30 20:33:30

How can I replace all the li of a ul in JQuery, I don't want add new item to the list by using append rather I want a new list with new li elements in the same ul.

如何在JQuery中替换ul中的所有li,我不希望使用append将新项添加到列表中,而我希望在同一ul中使用新的li元素列表。

I have tried

我努力了

for (index = 0; index < users.length; ++index) {
$('#users').replaceChild(users[index].UserName, $('#users').childNodes[index]);
}

HTML

<div class="col-md-4" style="margin:auto">
    <h2 class="text-success">Users</h2>
    <ul id="users" style="list-style:none"></ul>
</div>

but it only add the last element of the Array to the ul how can I create a new ul when every time I got a new list?

但它只是将数组的最后一个元素添加到ul中,每当我有新列表时如何创建新的ul?

2 个解决方案

#1


3  

It would be better if you include an example of your array. I made a snippet, hope it helps.

如果你包含一个数组的例子会更好。我做了一个片段,希望它有所帮助。

var array = ["New li 1", "New li 2", "New li 3"];

$('#load').click(function(){

  $('#list').empty();
  $.each(array, function( key, value ) {
    $('#list').append('<li>' + value + '</li>');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="list">
  <li>Old li 1</li>
  <li>Old li 2</li>
  <li>Old li 3</li>
</ul>

<button id="load">Load array</button>

#2


1  

You could use jQuery .replaceWith() function.

你可以使用jQuery .replaceWith()函数。

simply use the following code

只需使用以下代码即可

$('#users').replaceWith( "<li>New Item</li>" );

Refer this article .

参考这篇文章。

#1


3  

It would be better if you include an example of your array. I made a snippet, hope it helps.

如果你包含一个数组的例子会更好。我做了一个片段,希望它有所帮助。

var array = ["New li 1", "New li 2", "New li 3"];

$('#load').click(function(){

  $('#list').empty();
  $.each(array, function( key, value ) {
    $('#list').append('<li>' + value + '</li>');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="list">
  <li>Old li 1</li>
  <li>Old li 2</li>
  <li>Old li 3</li>
</ul>

<button id="load">Load array</button>

#2


1  

You could use jQuery .replaceWith() function.

你可以使用jQuery .replaceWith()函数。

simply use the following code

只需使用以下代码即可

$('#users').replaceWith( "<li>New Item</li>" );

Refer this article .

参考这篇文章。