Can't get data from element by clicking

29 Views Asked by At

everybody, i've been little stuck on one thing. I have code like this in JavaScript, JQuery. And those lower part with click, i just can't get data-num attribute, from clicked element. I've tried 100 ways to do it, but it's always undefined(but if i cheking out elements through developer tool, this 'data-num' realy exists), or crushing or doesen't working.

let tumbArr = [];
for (x = 0; x < imgARR.length; x++) {
    let thumb = document.createElement('button');
    $(thumb).css('background-image', 'url(' + images[x].src +')');
    elements.append(thumb);
    $(thumb).attr('id', 'thumb' + x)
    $(thumb).attr('data-num', x);
    tumbArr[x] = $(thumb);
    $(thumb).attr('class', 'thumbs');    
}
$('#thumbCase').append(elements);

// this part bellow
$('.thumbs').click(()  =>  {
    s = $(this).attr('data-num');
    imgSet(s);
})

When i was making an toDO app, everything was working this way...

addButton.click(() => {
    clickCount++;
    let newLI = document.createElement('li');
    newLI.textContent = addIN.value;
    elements.append(newLI);
    ul.append(elements);
    $(newLI).addClass('donePlan');
    $(newLI).attr('id','plan' + clickCount );
   
    del = document.createElement('button');
    $(del).addClass('delbutton');
    $(del).html('<img src="./delete_ic_icon.png">');
    newLI.append(del);
    $(del).attr('data-plan', '#plan' + clickCount)
   ** let planID = $(this.del).attr('data-plan');
    
   
    $(del).click (()=> {
        $(planID).remove();**
    })
   
})

Help me please, and thank you

I've tried to make .thumbs class like variable, to select buttons exeptionaly, ive made an array from this buttons in a loop tumbArr[x] = $(thumb), but it just doesen't works like i want, and like i think it logicaly should work.

1

There are 1 best solutions below

1
Alexander Nenashev On BEST ANSWER
  • You use an arrow function in which this works differently. this in an arrow function is this of the outer scope. So you should either use Event::currentTarget in an arrow function instead of this or use an usual function(){}.

  • Seems you try to delegate the click event to the parent container .thumbs. In this case this will be the container's DOM element and the handler will react on all click while you need clicks only on the buttons. You should use the special delegate function signature so this would point to the clicked button.

So the arrow function option:

$('.thumbs').on('click', 'button', event => {
    s = $(event.currentTarget).attr('data-num');
    imgSet(s);
})

The function option:

$('.thumbs').on('click', 'button', function() {
    s = $(this).attr('data-num');
    imgSet(s);
})