从表单的select选项的值中获取jquery数据属性

Nor*_*man 3 jquery

我试图dataoptions下面的表单中获取值,所以我可以在jQuery中使用它们,但我似乎似乎没有成功.我想做的很简单,你会在下面的代码中看到.我怎么能这样做?

$('#selectForm').click(function(e) {
        e.preventDefault();

        var action = $(this).data('id');
        var type = $(this).data('name');

        console.log(action+' '+type);
    });
Run Code Online (Sandbox Code Playgroud)

// jQuery的

<form id="selecttest">
    <label for="fruit">Please select at least two fruits</label><br>
        <select id="fruit" name="fruit" size="5">
            <option data-id="1" data-name="norman">Banana</option>
            <option data-id="2" data-name="james">Apple</option>
            <option data-id="3" data-name="lars">Peach</option>
            <option data-id="4" data-name="john">Turtle</option>
        </select>
        <input type="submit" id="selectForm" value="Validate Selecttests">
    </form>
Run Code Online (Sandbox Code Playgroud)

Ele*_*len 15

这是演示 - http://jsfiddle.net/tnVfV/

这是代码:

$('#selectForm').click(function (e) {
    e.preventDefault();

    var action = $('#fruit option:selected').attr('data-id');
    var type = $('#fruit option:selected').attr('data-name');

    console.log(action + ' ' + type);
});
Run Code Online (Sandbox Code Playgroud)

data-id并且data-name是选项的属性.有本机属性id,name你可以使用...


好的,因为tymeJV评论这里的代码使用data():

$('#selectForm').click(function (e) {
    e.preventDefault();

    var action = $('#fruit option:selected').data('id');
    var type = $('#fruit option:selected').data('name');

    console.log(action + ' ' + type);
});
Run Code Online (Sandbox Code Playgroud)

演示http://jsfiddle.net/tnVfV/1/