Home > OS >  Changed data attribute not recognized in jquery selector
Changed data attribute not recognized in jquery selector

Time:11-30

I've the following html structure

<body data-page="first">
   <div class="start">Test</div>
</body>

and the following js

$('body[data-page="first"] .start').on('click',function (){
    body.attr('data-page','second');
});
$('body[data-page="second"] .start').on('click',function (){
    console.log('Test');
});

I would expect, that after the second click on .start, the console would show "Test", but it doesn't...

Can you tell me what I'm doing wrong?

Thanks in advance!

CodePudding user response:

The issue is that the page is rendered with the data-page set to first, and when you click again on it, that part of javascript still see "first", since is not rerendered, so you need a dynamic function, the read all the intereaction with that button, and than check wich value that attribute has. Like this you can make infinite cases, and still go on.

$('body .start').on('click',function (){
  const attr = $('body').attr('data-page');
  if(attr === 'first') {
    $('body').attr('data-page','second');
  } else {
    console.log('second');
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body data-page="first">
   <div class="start">Test</div>
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

And if you don't like the fact that is targetting all the "body" wich is weird, becouse you should have only 1 body, you can use an ID to target the right one

PS: is never a good idea to duplicate your function, if you can set everything in a dynamic function, that reads everything, is easier to debug in the feature, and is lighter and more clean to work on

CodePudding user response:

This method can help :

var timesClicked = 0;
  $('.start').on('click',function (){
    timesClicked  ;
    if (timesClicked>1) {
    console.log('Test');
    }
});
  • Related