问题
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]')
gets me
<section class="job-block" data-id="240"></section>
...
but
$('.running').each (index, element) =>
console.log element.closest('[data-id]').data('id')
throws
Uncaught TypeError: element.closest(...).data is not a function
回答1:
The closest() method that you are using is native JS method and which returns DOM element object since element
refers DOM element object.
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
Or wrap element by jQuery and use data() method.
$('.running').each (index, element) =>
console.log $(element.closest('[data-id]')).data('id')
Or wrap the
element
by jQuery and use jQuery closest() method.
$('.running').each (index, element) =>
console.log $(element).closest('[data-id]').data('id')
回答2:
Because they are DOM objects (as you rightly state) and not jquery objects, you can't apply jquery methods to DOM objects, you need to convert them to jquery objects.
$(element).closest...
回答3:
The element
contains a DOMElement, so you're calling the native closest() method, not the jQuery one. Hence the data()
method does not exist on the returned object.
To fix this, wrap element
in a jQuery object:
$('.running').each (index, element) =>
console.log $(element).closest('[data-id]').data('id')
回答4:
data()
is a jQuery method so you should call it on jQuery object instead of a DOM oject, so it should be $(element)
:
console.log $(element).closest('[data-id]').data('id')
Hope this helps.
来源:https://stackoverflow.com/questions/41545413/jquery-element-closest-attr-is-not-a-function-when-using-each