将jquery转换为反应组件或纯javascript

时间:2018-05-29 07:17:46

标签: javascript reactjs

我有简单的待办事项列表的示例工作jQuery代码。如何将其更改为纯javascript或反应js组件。

<div class="todo-list container">
  <ul class="list-your-todo">
    <li>
      <input type="text" name="name" class="form-control" placeholder="Name" value="" />
      <p class="deleteList">- Delete this</p>
    </li>
  </ul>
  <p class="addList">+ Add another</p>
</div>

$(function(){
  $('.addList').click(function(){
    var $liLength = $(".list-your-todo li").length;
    var list = $('.todo-list').find('.list-your-todo li:first').html();
    $('.todo-list ul').append('<li class="clearfix showIcon">' + list + '</li>');
  });  
  $(document).on('click', '.deleteList', function(){
    $(this).parent('li').remove();
  });
});

这是工作演示https://jsfiddle.net/LxyLg8hh/

1 个答案:

答案 0 :(得分:1)

转换为纯JavaScript是相当简单的,虽然有点冗长,你需要再添加一个由jQuery自动执行的元素存在检查。

&#13;
&#13;
const addList = document.querySelector('.addList');

addList.addEventListener('click', event => {
  const liLength = document.querySelectorAll('.list-your-todo li').length;
  let list = document.querySelector('.todo-list li');
  list ? list = list.innerHTML : list = undefined;

  const item = document.createElement('li');
  item.className = 'clearfix showIcon';
  item.innerHTML = list;
  document.querySelector('.todo-list ul').appendChild(item);
});

document.body.addEventListener('click', event => {
  if (event.target.className === 'deleteList') {
    event.target.parentNode.remove();
  }
});
&#13;
.todo-list {
  padding: 50px 0px;
  position: relative;
  width: 500px
}
ul {
  list-style: none;
}
li {
  margin-bottom: 40px;
  line-height: 24px
}
input {
  margin-bottom: 10px;
}
.deleteList, .addList {
  cursor: pointer;
  position: absolute;
  font-weight: bold;
  font-size: 20px;
}
.deleteList {
  right: 0;
}
.addList {
  left: 0;
}
&#13;
<div class="todo-list container">
  <ul class="list-your-todo">
    <li>
      <input type="text" name="name" class="form-control" placeholder="Name" value="" />
      <p class="deleteList">- Delete this</p>
    </li>
  </ul>
  <p class="addList">+ Add another</p>
</div>
&#13;
&#13;
&#13;