質問

On click of one of the options I am trying to get the data value from the 'ul li a' and place it into button below, I've set up a fiddle example here: http://jsfiddle.net/q5j8z/4/

But cant seem to get it working

$('ul li a').click(function(e) {
    e.preventDefault();

    var value = $(this).data();

    $('.button').data('value');
});

Does anyone have any ideas please?

役に立ちましたか?

解決

You can do this:

$('ul li a').click(function (e) {
    e.preventDefault();
    var value = $(this).data('value');
    $('.button').data('value', value);
    console.log($('.button').data('value'));
});

Here, $(this).data('value') is used to get the data attribute value of the link.

and $('.button').data('value', value) is used to set the data attribute value of the button.

Using, console.log($('.button').data('value')); you can check the console the data value being set.

FIDDLE DEMO

For more info:- .data() API Documentation

他のヒント

Use it like this:

var value = $(this).data('value');

And then:

$('.button').data('value', value);

You are not assigning the value data to the button actually. Try this:

$('ul li a').click(function(e) {
    e.preventDefault();

    var value = $(this).data();

    // assign the value form the clicked anchor to button value data
    $('.button').data('value', value);

    console.log($('.button').data('value'));
});

Try this:

$('ul li a').click(function(e) {
        e.preventDefault();

        var value = $(this).data('value');

        $('.button').data('value', value);
    });

You can see the value of the button with console.log into your console with:

console.log('data: '+$(".button").data("value"));

First off you are are you trying to insert the value of variable value or 'value' literal?

data() is meant to be used similarily to attr('attr-name', attr_value) like below:

$('ul li a').click(function(e) {
    e.preventDefault();  
    var value = $(this).data('value');
    $('.button').data('value', value);
});

The above works in your fiddle.

Please note that you don't need to specify data- prefix because Jquery does that automatically

So ensure you are using the right attribute for value below

$('ul li a').click(function(e) {
    e.preventDefault();
    var value = $(this).data('value');
    $('.button').data('value', value);
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top