[英]es6 class find array object class from element
I have 2 classes parent/child.我有 2 个班级的父母/孩子。 In the parent class I need a way to return/find the child class from the clicked on element.在父 class 中,我需要一种方法从单击的元素返回/找到子 class。
I am getting: 'find(...).toggle is not a function'我得到:'find(...).toggle 不是函数'
Here in a minimal example:这里有一个最小的例子:
class card { constructor(parent, element) { this.parent = parent; this.element = element; } toggle(expand) { //Do stuff } } class cards { constructor() { this.element = $(".cards"); this.cards = []; this.element.children(".card").each((obj, el) => { console.log(el); this.cards.push(new card(this, $(el))); }); $(document).click((event) => { var clickedOn = $(event.target); var $thisClosest = clickedOn.closest(".card"); find($thisClosest).toggle(); }); } find(element) { this.cards.forEach((obj, el) => { if ($(el) == element) return obj; // need to return the class card }); }; } var my_a = new cards();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <div class="cards"> one asdf <div class="card">card 1 asdf</div> <div class="card">card 2 asdf</div> </div>
You should use this.cards.find
instead of this.cards.forEach
as Array.forEach
does not return any value .您应该使用this.cards.find
而不是this.cards.forEach
因为Array.forEach
不返回任何值。
Array.find
will return first element from array that matches the condition. Array.find
将返回数组中与条件匹配的第一个元素。
find(element) {
return this.cards.find((card) => card.element.is(element)));
};
I also used jQuery's.is() as a more robust way to compare elements.我还使用jQuery's.is()作为比较元素的更可靠的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.