How do I add a class to appended element using Jquery?

问题: How to add 'list-group-item' class while appending an element with jquery? After appending an <li> to <ul id="todoList"> class property not working as i expec...

问题:

How to add 'list-group-item' class while appending an element with jquery?

After appending an <li> to <ul id="todoList"> class property not working as i expected.

  $("#todoList").append($('<li>', {
    text: $('#todoInput').val(),

    class: $('list-group-item') // this is not working
  }));

回答1:

You can do:

$("#todoAddBtn").on("click", function() {
  $("#todoList").append($('<li>', {
    text: $('#todoInput').val(),
    class: 'list-group-item' // <-- Class name should be an string
  }));
  $('#todoInput').val(''); // Clear input..
});
.list-group-item {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="todoList"></ul>
<input id="todoInput">
<button id="todoAddBtn">Add</button>


回答2:

When you do class: $('list-group-item'), you're basically creating an object that you add to the class. You just want a string that is the class-name, and not an object. All you need is class: 'list-group-item'.

$("#todoAddBtn").on("click", function() {
  $("#todoList").append($('<li>', {
    text: $('#todoInput').val(),
    class: 'list-group-item'
  }));
});

回答3:

If you want to add this 'list-group-item' then change it to

class: 'list-group-item'
  • 发表于 2019-03-02 14:47
  • 阅读 ( 135 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除