我正在尝试在设置数据属性
的链接上获取焦点方法(触摸、鼠标或键盘)。
$(function() {
var i,
r = document.getElementsByTagName("a")[0];
if ("ontouchstart" in window) {
document.addEventListener("touchstart", function(event) {
i = "touch";
}, true);
}
else {
document.addEventListener("mousedown", function(event) {
i = "mouse";
}, true);
}
document.addEventListener("keydown", function(event) {
i = "keyboard";
}, true);
})
问题是我只得到用 jQuery 编写最后一部分的结果:
$("a").focus(function() {
$(this).attr("data-focus-method", i)
})
$("a").blur(function() {
$(this).removeAttr("data-focus-method")
})
我想用纯 JavaScript 编写整个代码。我尝试过以下方法:
r.addEventListener("focus", function() {
r.setAttribute("data-focus-method", i);
});
r.addEventListener("blur", function() {
r.removeAttribute("data-focus-method");
});
但是这不起作用。 有人可以帮我吗?
最佳答案
我建议使用querySelectorAll方法并使用forEach来迭代节点列表
document.querySelectorAll("a").forEach((link) => {
link.addEventListener("focus", function() {
this.setAttribute("data-focus-method", i);
});
link.addEventListener("blur", function() {
this.removeAttribute("data-focus-method");
});
});
关于javascript - 如何将此 jQuery 代码转换为纯 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59843271/