0

ある関数で jQuery.data を使用してデータを保存し、別の関数でアクセスしようとしていますが、最初の関数の外ではデータが未定義になります。コードを見てください:

$("input:radio[name=gender]:checked").each(function()
{
    var genderChosen = $(this).val();
    alert(genderChosen);
    var gender = $(".gender");
    jQuery.data(gender, 'genderChosen', genderChosen);
    alert(jQuery.data(gender, 'genderChosen'));
    // Displays "male" or "female" depending on what's selected
});

var gender = $(".gender");
alert(jQuery.data(gender, 'genderChosen'));
// Displays "undefined"

誰かが元の関数の外でこのデータを取得するのを手伝ってくれませんか? それが jQuery.data メソッドの要点だと思いました...

ありがとう!

4

1 に答える 1

1

You should set it like this:

$('.gender').data('genderChosen', genderChosen);

You should get it like this:

var genderChosen = $('.gender').data('genderChosen');

And you are right. You should be able to access the attached data from anywhere.

And yes. In theory jQuery.data() does the same as .data() when you are attaching data to DOM elements. I'm not sure why it doesn't work for you, maybe there are browser specific quirks around this.

于 2013-03-28T19:32:49.717 に答える