jQuery element.closest(...).attr在使用每个函数时不是函数 [英] jQuery element.closest(...).attr is not a function when using each
本文介绍了jQuery element.closest(...).attr在使用每个函数时不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当遍历某些DOM元素时,我发现无法对它们使用.data或.attr:
When iterating over some DOM elements I found it impossible to use .data or .attr on them:
$('.running').each (index, element) =>
console.log element.closest('[data-id]')
得到我
<section class="job-block" data-id="240"></section>
...
但是
$('.running').each (index, element) =>
console.log element.closest('[data-id]').data('id')
抛出
未捕获的TypeError:element.closest(...).data不是函数
Uncaught TypeError: element.closest(...).data is not a function
推荐答案
The closest()
method that you are using is native JS method and which returns DOM element object since element
refers DOM element object.
有几个选项可以获取属性值,可以从
dataset
获取. 属性:
There are several options to get the attribute value, either get from
dataset
property :
$('.running').each (index, element) =>
console.log element.closest('[data-id]').dataset.id
或使用jQuery包装元素,然后使用
data()
方法.
Or wrap element by jQuery and use
data()
method.
$('.running').each (index, element) =>
console.log $(element.closest('[data-id]')).data('id')
或使用jQuery包装
element
并使用jQuery closest()
方法.
Or wrap the
element
by jQuery and use jQuery closest()
method.
$('.running').each (index, element) =>
console.log $(element).closest('[data-id]').data('id')
这篇关于jQuery element.closest(...).attr在使用每个函数时不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文