javascript - 获取包含它的最接近元素的特定数据属性的值 TypeError
问题描述
在我的库中,我想编写一个小函数closest()
,尤其是获取特定data-attribut
的最接近元素的值,因为在我的应用程序中,我需要经常使用它。:D
但我只被控制台告知:
TypeError:x.getAttribute 不是函数
var $ = function(s) {
var x;
var obj = {
myLib(s) {
return x || querySelectorAll(s);
},
myFunction(s) {
if (s.startsWith('data-')) { // in this block is sth. wrong
x = [x[0].closest('*["' + s + '"]')];
return x.getAttribute(s);
} else {
x = [x[0].closest(s)];
return this;
}
}
};
x = obj.myLib(s);
return obj;
};
////////// usage examples
// get the value of attribute "data-wrestler"
var dv = $('.kilo').myFunction('data-wrestler');
console.log(dv);
// select the closest element by selector
var ce = $('.kilo').myFunction('.uniform');
console.log(ce);
// would select the closest element with specific data-attribut by selector
var da = $('.kilo').myFunction('*["data-wrestler"]');
console.log(da);
<div id="foxtrott">
foxtrott
<div class="uniform" data-wrestler="hulkster">
uniform
<div class="charlie">
charlie
<div class="kilo">
kilo
</div>
</div>
</div>
</div>
解决方案
报价
[data-wrestler]
- 删除它们x = [x[0].closest('[' + s + ']')];
您使用 document.querySelectorAll - 它返回一个集合,因此您需要使用 [0]
返回 x[0].getAttribute(s);
或更改为 document.querySelector
推荐阅读
- c# - ConcurrentDictionary AddOrUpdate 方法抛出 IndexOutOfRangeException
- php - 如何从 Google 检索“我的商家”评论
- php - 使用友好 URL 时如何启用对指定 URL 的访问?
- sails.js - 如何在 SailsJS 1.x 中使用蓝图路由实现行级权限?
- c++ - C/C++ memcpu 基准测试:测量 CPU 和挂墙时间
- ruby-on-rails - 如何使用 rspec 测试 json fast api rails?
- autosys - Autosys - 是否可以在作业错误日志中添加时间戳?
- python - 我怎样才能格式化这个输出有一个%?
- python - 遍历目录 h5 文件的所有文件夹
- xstate - 如何从 xstate 中的状态获取所有可能的转换