2011-12-18 38 views
0

如果我有HTMLjQuery的返回选定的选项属性值

<select id="autoplay"> 
    <option data-autoplay="">no</option> 
    <option data-autoplay="1">yes</option> 
</select> 

如何使用jQuery可以我就返回data-autoplay值到被选择的选项,并将其设置为变量var autoplay = *selected value*

所以如果我选择no它没有返回值,如果我选择yes它返回1,因此var autoplay = "1";

回答

1
下面的代码

尝试,

$("#autoplay option:selected").attr("data-autoplay"); 

$("#autoplay option:selected").data("autoplay"); 
1

可以使用attr()方法来获得一个属性的值:

var autopplay = $('#autoplay option:selected').attr('data-autoplay'); 

if (!autoplay || autoplay == '') { 
    // an empty string was returned 
} 
else if (autoplay == 1) { 
    /* remember not to trust your users, so validate in/on the server 
     if you're storing the variable/result... 
    // 1 was returned 
} 

有可能也使用data('autoplay'),这将看data-前缀属性与下面的data-选择(自动播放)匹配的字符串,所以在这种情况下,它会寻找:data-autoplay(有点明显,我想)。

参考文献:

相关问题