我有以下JS / prototypeJS,我想用完整的vanilla JS编写。我希望单击一个元素(具有相同类的多个元素中的一个 - faq-container
)并添加一个特定的类(在本例中为faq-display
)并仅将此类添加到父容器(faq-block
)。
我知道纯JS函数与.parent.addClass
有关,但找不到我的情况的相关示例。
prototypeJs行是:
faqContainers[i].addEventListener('click', function(e) {
和
var faqToggle = e.target.up('.faq-block');
脚本文件是:
var faqContainers = document.getElementsByClassName('faq-container');
for (var i = 0; i < faqContainers.length; i++) {
faqContainers[i].addEventListener('click', function(e) {
var faqToggle = e.target.up('.faq-block');
if (faqToggle.classList.contains('faq-display')) {
faqToggle.classList.remove('faq-display');
} else {
faqToggle.classList.add('faq-display');
}
});
}
&#13;
非常感谢!
答案 0 :(得分:1)
以下是将closest()替换为PrototypeJS up()的示例:
$connection = new \yii\db\Connection([
'dsn' => $dsn,
'username' => $username,
'password' => $password,
]);
$connection->open();
$command = $connection->createCommand('SELECT * FROM post')->....;
&#13;
var faqContainers = document.getElementsByClassName('faq-container');
for (var i = 0; i < faqContainers.length; i++) {
faqContainers[i].addEventListener('click', function(e) {
var faqToggle = e.target.closest('.faq-block');
if (faqToggle.classList.contains('faq-display')) {
faqToggle.classList.remove('faq-display');
} else {
faqToggle.classList.add('faq-display');
}
});
}
&#13;
.faq {
display: none;
}
.faq-block.faq-display .faq {
display: block;
}
&#13;