문제

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?

도움이 되었습니까?

해결책

Use Has Attribute Selector

$('a[data-title], button[data-title]').on('click', function() {
    // do something
});

다른 팁

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 !== "".

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top