简体   繁体   English

是否可以将价值传递给 <div data-value=“” > 通过jQuery?

[英]Isit possible to pass value into <div data-value=“” > by jquery?

This is my html code 这是我的html代码

<div  data-percent="" ></div>

This is my javascript 这是我的JavaScript

 function retrieveProgressbar(){
                  $.ajax({
                    type:"post",
                    url:"retrieveprogressbar.php",
                    data:"progressbar",
                    success:function(data){
                    $(this).data("percent").html(data); 
                    }
                  });
                }

                retrieveProgressbar();

I need the value retrieved by ajax to be displayed in the data-percent="". 我需要ajax检索的值才能显示在data-percent =“”中。 I am not sure how to do that. 我不确定该怎么做。 I have another javascript that needs to use this value to execute. 我还有另一个需要使用此值来执行的JavaScript。

Need to use .attr() method. 需要使用.attr()方法。

<div  data-percent="" id="datadiv"></div>

    <script>
        function retrieveProgressbar() {
            $.ajax({
                type: "post",
                url: "retrieveprogressbar.php",
                data: "progressbar",
                success: function (data) {
                    //$("#datadiv").attr("data-percent", data);
                    // OR
                    $(this).attr("data-percent", data);
                }
            });
        }

        retrieveProgressbar();
    </script>

HTML: HTML:

<div  data-percent=""></div>

The proper way to assign data on jquery is 在jQuery上分配 data的正确方法是

var new_data_value = "I will be the new value.";
$("div").data("percent",new_data_value);    

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. .data()方法允许我们以一种安全的方式将任何类型的数据附加到DOM元素上,以防止循环引用,从而避免内存泄漏。

You can retrieve the data by: 您可以通过以下方式检索数据:

var value = $( "div" ).data( "percent" );

.attr() on the other hand set/get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element. 另一方面, .attr()为匹配元素集中的第一个元素设置/获取属性值,或者为每个匹配元素设置一个或多个属性。

It does not attach data of any type to DOM elements. 它不会将任何类型的数据附加到DOM元素。

$("div").attr("data-percent",data_value); 

Sources: https://api.jquery.com/data/ 资料来源: https : //api.jquery.com/data/

http://api.jquery.com/attr/ http://api.jquery.com/attr/

是的,您可以改用.attr(函数。

$(this).attr("data-percent", your_value); 

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

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