[在我的库中,我想为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