Reputation:
I don't know if the title of the question is correct, because i don't know exactly what is this.
I have this piece of code:
$actual.find('h2').addClass('event__change')
.append('<span class="event__arrow" aria-hidden="true">▼</span>')
.append(function () {
var self = $(this);
var list = '<ul class="dropdown hidden">';
$('.event').each(function (index) {
if ($(this).find('h2')[0] != self[0]) {
list += "<li data-index='" + index + "'>" + $(this).find('h2').text() + '</li>';
}
});
return list;
})
.click(function () {
if ($(this).attr("data-expanded") == true) {
$(this).find("ul").toggleClass('hidden');
$(this).attr("data-expanded", false);
} else {
$(this).find("ul").toggleClass('hidden');
$(this).attr("data-expanded", true);
}
});
And i was trying to use like this:
$actual.find('h2').addClass('event__change');
$actual.append('<span class="event__arrow" aria-hidden="true">▼</span>');
$actual.append(function () {
var self = $(this);
var list = '<ul class="dropdown hidden">';
$('.event').each(function (index) {
if ($(this).find('h2')[0] != self[0]) {
list += "<li data-index='" + index + "'>" + $(this).find('h2').text() + '</li>';
}
});
return list;
});
$actual.click(function () {
if ($(this).attr("data-expanded") == true) {
$(this).find("ul").toggleClass('hidden');
$(this).attr("data-expanded", false);
} else {
$(this).find("ul").toggleClass('hidden');
$(this).attr("data-expanded", true);
}
});
But if i try change to the second code, the effect will broke totally, and i want understand why..
Upvotes: 0
Views: 32
Reputation: 3892
You can easily fix the code:
var $actual_ = $actual.find('h2');// redefine the target of next actions
$actual_.addClass('event__change');
$actual_.append('<span class="event__arrow" aria-hidden="true">▼</span>');
$actual_.append(function () {
var self = $(this);
var list = '<ul class="dropdown hidden">';
$('.event').each(function (index) {
if ($(this).find('h2')[0] != self[0]) {
list += "<li data-index='" + index + "'>" + $(this).find('h2').text() + '</li>';
}
});
return list;
});
$actual_.click(function () {
if ($(this).attr("data-expanded") == true) {
$(this).find("ul").toggleClass('hidden');
$(this).attr("data-expanded", false);
} else {
$(this).find("ul").toggleClass('hidden');
$(this).attr("data-expanded", true);
}
});
Upvotes: 0
Reputation: 944544
In the first example you are chaining off the results of find("h2")
.
In the second you are working directly on $actual
.
These are different collections of elements.
Upvotes: 1