简体   繁体   English

jQuery在更改时获取属性值

[英]Jquery get attribute value as it changes

I have the following HTML 我有以下HTML

<div class="element" data-settings={"apples":1,"bananas":4,"speed":300}>
</div>

The values in data-settings can be changed in my app however the js code that updates the values is written in Reactjs, is minified and unreadable. 可以在我的应用程序中更改data-settings的值,但是更新值的js代码是用Reactjs编写的,因此已缩小且不可读。 I just want to get some values using simple jquery in my own js. 我只想在自己的js中使用简单的jquery获得一些值。

In my own js, when I click .element I want to get the updated value of data-settings . 在我自己的js中,当我单击.element我想获取data-settings的更新值。

My code: 我的代码:

$('.element').on('click', function() {
    console.log( $(".element").data("settings") );
});

It returns the data-settings values but when I update a setting and click .element again it does not return the updated values. 它返回data-settings值,但是当我更新设置并再次单击.element时,它不会返回更新后的值。

For example, I update apples to 8 in my app. 例如,我在应用程序中将apples更新为8。 I see data-settings={"apples":8,"bananas":4,"speed":300} in the HTML but in my console log, apples are still 1. 我在HTML中看到data-settings={"apples":8,"bananas":4,"speed":300} ,但在控制台日志中,apples仍然是1。

I also tried: 我也尝试过:

$('body').on('click', '.element', function() {
    console.log( $(".element").data("settings") );
});

and does not work. 并且不起作用。

How can I see the live changes to the data attribute settings in my js? 如何查看js中数据属性settings的实时更改?

You should use both JSON.parse() and JSON.stringify() properties 您应该同时使用JSON.parse()JSON.stringify()属性

 $(document).on('click', '.show', function() { // Convert to JSON $settings = JSON.parse($(".element").attr("data-settings")); $settings.speed = getRandomInt(500); // Update the value $settings.apples = getRandomInt(10); // Update the value $settings.bananas = getRandomInt(100); // Update the value // Convert to string $settings = JSON.stringify($settings); // Update in the Div $(".element").attr("data-settings",$settings); $('.result').append('<li>'+$settings+'</li>'); }); function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max) +1); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="element" data-settings={"apples":1,"bananas":4,"speed":300}> Click the "Generate" button to Update the value in the Div. Here I added a function to generate random integer values. </div> <button class="show">Show</button> <ul class="result"> <li>{"apples":1,"bananas":4,"speed":300}</li> </ul> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM