$('a[data-title], button[data-title]').on('click', function() {
// do something
});
Access all custom data attributes on certain elements
-
01-07-2022 - |
문제
I want to execute a function on click only from elements that have a custom data attribute (data-title
) set. Currently they are just a
and button
elements.
Why does this code execute on all a
and button
elements even if no data-title
is set?
$('a[data-title!=""], button[data-title!=""]').on('click', function() {
// do something
});
What should I change?
해결책
다른 팁
What you need is attribute exists selector
$('a[data-title], button[data-title]').on('click', function() {
// do something
});
why?
In your condition you are checking data-title!=""
, but if the element does not have the attribute data-title
the attribute value will be null
not ""
(empty string), thus the test result !== check
will return true because null !== ""
.
제휴하지 않습니다 StackOverflow