将javascript变量存储在data属性中并检索它

时间:2014-09-04 13:59:25

标签: javascript jquery

我这里有一个jsfiddle - http://jsfiddle.net/0zppxL95/

我正在尝试在html数据属性中存储jQuery变量 然后在单击按钮时获取该值。

是否可以这样做,或者我如何存储javascript变量然后检索它。

这将是一个循环,所以我想将它存储在连接到按钮的这个对象的变量上,这样我就可以说当点击这个按钮时得到这个变量。

        var test = 'Hello';

        $('button').click(function(){
            var output = $(this).parent().attr('data-text');
            alert(output);
        })

3 个答案:

答案 0 :(得分:2)

您可以设置attr值,然后像现在一样检索它:

var test = 'Hello';

$('button').click(function(){
    //set the variable
    $(this).parent().attr('data-text', test);

    //get the variable
    var output = $(this).parent().attr('data-text');
    alert(output);
})

Living example

答案 1 :(得分:1)

要设置您需要使用的数据属性:

$(this).parent().data('text',test);

<强> Working Demo

答案 2 :(得分:1)

使用.data(key,value)

设置数据
$(this).parent().data('text',test);

DEMO