Javascript 翻译jquery代码给我带来了麻烦,this.querySelector不是一个函数,来自$(this.find(';img';)
所以我并没有发现类似的问题,我认为相当于。find是querySelector,而“this”也存在于纯JS中,我认为类似的脚本可以工作,所以我希望它也可以工作 我正在翻译这个函数Javascript 翻译jquery代码给我带来了麻烦,this.querySelector不是一个函数,来自$(this.find(';img';),javascript,jquery,find,Javascript,Jquery,Find,所以我并没有发现类似的问题,我认为相当于。find是querySelector,而“this”也存在于纯JS中,我认为类似的脚本可以工作,所以我希望它也可以工作 我正在翻译这个函数 $('.my-gallery').each(function() { $(this).find('a').each(function() { $(this).attr('data-size', $(this).find('img').get(0).naturalWidth + 'x' + $(this)
$('.my-gallery').each(function() {
$(this).find('a').each(function() {
$(this).attr('data-size', $(this).find('img').get(0).naturalWidth + 'x' + $(this).find('img').get(0).naturalHeight);
});
});
这是我目前翻译的代码
var elements = document.querySelectorAll('.my-gallery');
Array.prototype.forEach.call(elements, function(){
var a = this.querySelector('a');
Array.prototype.forEach.call(a, function(){
this.getAttribute('data-size', this.querySelector('img').naturalWidth + 'x' + this.querySelector('img').naturalHeight);
});
});
所有东西都会找到,但它会被困在这个.querySelector('img')。naturalWidth,我不知道为什么因为这个.getAttribute工作正常,所以为什么我不能查询这个元素的chilren你可以做的不仅仅是翻译它。您可以对其进行改进,这样就不必使用
此
。根据jQuery代码,您似乎还试图设置属性而没有获取它
下面的内容应该适合您
document.querySelectorAll('.my-gallery a').forEach(function(anchor) {
anchor.setAttribute('data-size', anchor.querySelector('img').naturalWidth + 'x' + anchor.querySelector('img').naturalHeight);
});
将
this.querySelector
替换为document.querySelector
这根本不起作用,我想我需要从这个子级获取属性,或者如何获取属性,只需将其更改为document doeasnot work我会得到另一个错误linkEl.getAttribute(…)为null,因此,可能是我写错了代码,或者这个东西被误用了。这看起来像是正确的翻译,它比jquery代码imo更可读。好的,在进一步测试之后,我得到了t是未定义的错误Uncaught TypeError:t是未定义的错误与代码无关,除非您更改了变量。JS控制台将告诉您错误在哪一行。