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

泪湿孤枕 提交于 2019-12-01 20:30:34

问题


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 how to attach an event listener in this case though?


回答1:


`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.




回答2:


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.



来源:https://stackoverflow.com/questions/11057748/how-to-monitor-when-the-body-data-attribute-changes-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!