gpt4 book ai didi

javascript - 如何将此函数从 jquery 转换为纯 javascript?

转载 作者:行者123 更新时间:2023-11-30 16:15:49 26 4
gpt4 key购买 nike

我已经尝试了很多排列,我太依赖 jquery 并且对于这个特定的任务我必须没有...

我现在卡住了,无法将其转换为使用纯 javascript:

			$.root_ = $('body');
$.root_.on('click', '[data-action="toggle"]', function(e) {
var $this = $(this),
element = $(this).attr("data-target") || 'body';
$(element).toggleClass($(this).attr("data-class"));
//clear memory reference
$this = null;
element = null;

//save settings
//saveSettings();

});
.red-bg {
background: #3d1c24;
}
.white-bg {
background: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>

<head></head>

<body>

<a href="#" data-action="toggle" data-class="red-bg">Change BG (RED)</a><br>
<a href="#" data-action="toggle" data-class="white-bg">Change BG (WHITE)</a>

</body>

</html>

最佳答案

document.body.addEventListener('click', function(e) {
var target = e.target; // convenience
var dataset = target.dataset; // convenience
var selector, element;
if (dataset.action == 'toggle') {
selector = dataset.target || 'body';
element = document.querySelector(selector);
if (element) {
element.classList.toggle(dataset['class']);
}
}
//save settings
//saveSettings();
});

NOTE this uses node.classList and node.querySelector which probably doesn't work on old IE (older than 11 - don't know, do some research) - but you can get workarounds for for such old tech

注意:如果 dataset.target 所针对的元素可能导致多个元素 - 请改为执行此操作

document.body.addEventListener('click', function(e) {
var target = e.target; // convenience
if (target.dataset.action != 'toggle' && target.parentNode.dataset.action == 'toggle') {
target = target.parentNode;
}
var dataset = target.dataset; // convenience
var selector, elements;
if (dataset.action == 'toggle') {
selector = dataset.target || 'body';
elements = document.querySelectorAll(selector);
if (elements.length) {
[].forEach.call(elements, function(element) {
element.classList.toggle(dataset['class']);
});
}
}
//save settings
//saveSettings();
});

关于javascript - 如何将此函数从 jquery 转换为纯 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35546251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com