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

前端 未结 3 1435
北恋
北恋 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();
    
     Result: 

    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.

提交回复
热议问题