How to monitor when the body 'data' attribute changes in jQuery?

前端 未结 3 1434
北恋
北恋 2021-01-18 16:44

I have data-segment attribute in my body tag that is changed by a slider. I need to trigger a function based on the value of this, when it is changed.

I\'m not sure

相关标签:
3条回答
  • 2021-01-18 16:52

    Since in my use case all of my .data('type', 'value') is set inside javascript block anyway, so in my case I just put a .change() chain right after the .data(...) and access the update using the normal $("#oh-my-data").change()

    Which works fine for me, see the demo.

    $("#oh-my-data").change(function() {
      $("#result").text($("#result").text() + ' ' + $(this).data('value'));
    })
    
    $("#oh-my-data").data('value', 'something1').change();
    
    $("#oh-my-data").data('value', 'something2').change();
    
    $("#oh-my-data").data('value', 'something3').change();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id="oh-my-data" type="hidden" data-value="" /> Result: <span id="result"></span>

    But this solution have a problem, which is that if the .data() is set by an external library, then this will not work since you can't add the .change() on top of it.

    0 讨论(0)
  • 2021-01-18 17:09

    You can use MutationObserver, which is an API available in every browser and avoid polling with setInterval. If you have a reference to your element in element, you could do this:

    const mutationObserver = new MutationObserver(callback);
    mutationObserver.observe(element, { attributes: true });
    
    function callback() {
      // This function will be called every time attributes are
      // changed, including `data-` attributes.
    }
    
    

    Other changes in your element can be easily detected with this API, and you can even get the old and new values of the property that changes in your callback tweaking the configuration object in the call to observe. All the documentation about this can be read in MDN: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit

    0 讨论(0)
  • 2021-01-18 17:14

    `There is no reliable cross-browser way to receive an event when a DOM node attribute is changed. Some browsers support "DOM mutation events", but you shouldn't rely on them, and you may Google that phrase to learn about the ill-fated history of that technology.

    If the slider control does not fire a custom event (I would think most modern ones do), then your best bet is to set up a setInterval() method to poll the value.

    0 讨论(0)
提交回复
热议问题