Не работает селект по атрибуту | JQuery
$('*[redirect]').on('click', function() {
let direct = this.getAttribute('redirect');
console.log('redirect,', direct);
// core.mount(direct);
});
$('*[click]').on('click', function() {
let methodName = this.getAttribute('click');
if (methodName.length > 0) {
console.log('click,', methodName);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex justify-content-center align-items-center" id="header">
<span redirect="main" click="name" class="font-monospace fst-normal text-center text-uppercase fs-4">${appName}</span>
<span redirect="setting" class="icon position-absolute">${icons.setting}</span>
</div>
Странно то, что у меня находит элементы с [redirect], но совершенно не видит элементы с [click]. Что я делаю не так?
Ответы (2 шт):
Автор решения: Vadim
→ Ссылка
Звездочка зачем? Вообще, я бы более точный селектор на твоём месте выдумал ? (тем более, если html твой)
$('[redirect]').on('click', ({currentTarget, target})=>{
const direct = currentTarget.getAttribute('redirect');
const direct2 = target.getAttribute('redirect');
console.log('redirect:', direct, direct2);
});
$('[click]').on('click', ({currentTarget, target})=>{
const methodName = currentTarget.getAttribute('click');
const methodName2 = target.getAttribute('click');
console.log('click:', methodName, methodName2);
});
span{background:gainsboro;padding:6px;border-radius:3px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex justify-content-center align-items-center" id="header">
<span redirect="main" click="name" class="font-monospace fst-normal text-center text-uppercase fs-4">${appName}</span>
<span redirect="setting" class="icon position-absolute">${icons.setting}</span>
</div>
Автор решения: Sire IMPACTUS
→ Ссылка
Обернул скрипт ready и заработало.
$(document).ready(() => {
$('[redirect]').on('click', function () {
let direct = this.getAttribute('redirect');
core.mount(direct);
});
$('[click]').on('click', function (e) {
console.log(e);
let methodName = this.getAttribute('click');
if(methodName.length > 0) {
console.log(methodName);
}
});
});