单击时未删除jQuery数组元素

时间:2019-02-22 14:13:13

标签: jquery

我正在尝试在jQuery中构建一个简单的演示,以创建新元素并能够删除它们。我不确定为什么,但是我无法在jQuery中使用它。我可以使用JavaScript,并在此处构建了一个有效的演示:https://codepen.io/anon/pen/omrdmm

似乎无效的代码是这一部分:

/* NOT WORKING */
    $.each(removes, function(el) {
      el.on("click", function(){
        let removedId = $(this).parent().attr('data-id');
        $(this).parent().remove(); console.log('removed id ' + removedId);
        updateElements();
      });
    }); 

Codepen网址:https://codepen.io/anon/pen/OdeZrV

我在jQuery方面没有丰富的经验,也不知道为什么上面的方法不起作用。它应该仅遍历每个数组项(或。remove类)并添加一个事件侦听器,单击该事件侦听器将删除其父项(行)。

有人可以在这里解释具体出什么问题并演示如何解决吗?任何最佳编码实践将不胜感激。感谢您的帮助。

这是jQuery中的完整代码:

// defaults
var id = 1, objects = [], removes = $(".remove");
updateElements();

function createEntry() {
  id++;

  // create new element, append to #container & create new object
  var container = $('#container'),
      newEntry = $('<div/>'),
      title = 'title text here',
      description = 'description text here',
      remove = 'remove',
      dataId = id,
      obj = new Entry(title, description, remove);
  newEntry.addClass("entry");
  newEntry.html('<span class="title">' + title + '</span><span class="description">' + description + '</span><span class="remove">' + remove + '</span>');
  container.append(newEntry);
  newEntry.attr('data-id', id);

  updateElements();

  // constructor & push into array
  function Entry(title, description, remove) {
    this.title = title;
    this.description = description;
    this.remove = remove;
    this.id = id;

    objects.push(this);
  }

  // tests
  console.log('JSON.stringify(objects[0]): ' + JSON.stringify(objects[0]));
  console.log('obj.title: ' + obj.title);
  console.log('JSON.stringify(obj): ' + JSON.stringify(obj));
  console.log('obj.id: ' + obj.id);
}

function updateElements() {
  removes = $(".remove");
  listenForRemoves();

  function listenForRemoves() {
    
    /* NOT WORKING */
    $.each(removes, function(el) {
      el.on("click", function(){
        let removedId = $(this).parent().attr('data-id');
        $(this).parent().remove(); console.log('removed id ' + removedId);
        updateElements();
      });
    });    
  }
}
button { display: block }
.entry {
	width: 100%;
	display: block;
	padding: 10px;
	border: 1px solid #f5f5f5;
}
span {
  display: block;
  width: 100%;
}
section { background: lightgreen }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='btn' onclick='createEntry()'>Create</button>
<section id='container'>
	<div class='entry' data-id='1'>
		<span class='title'>title text here</span>
		<span class='description'>description text here</span>
		<span class='remove'>remove</span>
	</div>
</section>

0 个答案:

没有答案