Strange behavior when displaying an attribute using click ();

3

I am developing a script that requires calling a click() of a button because it is invisible on the page, however jQuery does not seem to return the updated attributes when they are changed. Here's an example:

$(function(){
    $('.hidden').on('click', function(){
        console.log($(this).data('s'));
        alert($(this).data('s')); 
    });
});
    
$('.visivel').on('click', function(){
    var d = new Date();
    var s = d.getSeconds();
    $('.hidden').attr('data-s', s).click();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonclass='visivel'>Cliqueme</button><buttonclass='hidden'data-s=''style='display:none;'>Invisivel</button>

Asyoucansee,whenyoutest,aalert()isgeneratedinformingthecurrentseconds,butifyouclickagainitshowsthesecondsofthefirstclick,eventhoughdata-sischanged,alertdoesnotreturnthenewsecond.IsthisajQuerybug?Ionlymanagedtosolveusingthis.dataset.ssothatalertworks,wouldyouliketoknowwhythisbehavior?Andthestructureisthesame,afunctioninsideandoutsidethe$(function(){}).

link

PS:

  

The structure should follow the one I put as an example, one of the   functions must be outside $ (function () {}), this is because the logic of   project requires this type of organization, I am using other   libraries.

    
asked by anonymous 05.08.2015 / 21:17

3 answers

6

jQuery works unpredictably when you mix the setter / getter of .attr('data-xx' and .data( . Please note that your code works if you use only .attr() or only .data() .

There are other questions that concern this issue ( this and this ). @bfavaretto described the problem there :

  

Checking the HTML5 dating attributes is actually a fallback. If a value is set to .data (), retrieve it with that same method, nor look at the attribute (nor for the dataset property of the element in question).

That is, the first time you run the code jQuery functions as a setter and assigns the data- to the element. Then you no longer use the engine and when you search for the value with .data() "he does not even see".

    
05.08.2015 / 21:49
2

The problem is how you are updating data-s , use method data and not attr

$(function(){
    $('.hidden').on('click', function(){
        console.log($(this).data('s'));
        alert($(this).data('s')); 
    });
});

$('.visivel').on('click', function(){
    var d = new Date();
    var s = d.getSeconds();
    $('.hidden').data('s', s).click();
})
    
05.08.2015 / 21:43
-2

Use the .data() attribute of jQuery. It is most suitable for working with data-attr in HTML.

$(function(){
    $('.hidden').on('click', function(){
        console.log($(this).data('s'));
        alert($(this).data('s')); 
    });
});

$('.visivel').on('click', function(){
    var d = new Date();
    var s = d.getSeconds();
    $('.hidden').data('s', s).click();
});
    
05.08.2015 / 21:35