用于自定义标记的Javascript选择器

时间:2014-04-22 16:40:57

标签: javascript jquery html

我需要能够在标记中获取自定义参数的.val()。标签看起来像这样:

option style="font-weight: normal" answerid="32" >text here< /option

为了使代码/标签自我解释,我想使用“answerid”而不是“name”,但我无法弄清楚如何获得它的价值。我当前的脚本如下所示:

<script>
$('select').change(function () {
     var optionSelected = $(this).find("option:selected");
     var valueSelected  = optionSelected.val("answerid");
     $.get("ticket.php?do=quickanswer&selected=" +valueSelected+ "", 
     function( data ) {
                $( ".quickanswer" ).html( data );
                });

     console.log(valueSelected);
 });
</script>

2 个答案:

答案 0 :(得分:1)

您可以使用 .attr()

var valueSelected  = optionSelected.attr("answerid");

<强> Fiddle Demo

答案 1 :(得分:0)

使用answerid作为属性是无效的HTML。使用自定义[data-*] attribute

,而不是使用无效标记
<option data-answer-id="32">text here</option>

然后,您可以利用jQuery's .data() method来访问该值:

answerId = optionSelected.data('answerId'); //32

.attr()也适用:

answerId = optionSelected.attr('data-answer-id'); //'32'

Please see my related answer for details as to why you'd use one over the other