【问题标题】:How can I get selected list attributes in JQuery如何在 JQuery 中获取选定的列表属性
【发布时间】:2014-04-26 21:29:05
【问题描述】:

单击按钮时,我不希望此警报框显示属性item_name。我有 JQuery。

这是我尝试使用的代码,但它不起作用

HTML

<select class="p1add1">
    <option class="op1" value="3.74" item_name='BOWL'>Bowl   - £3.74</option>
    <option class="op2" value="7.53" item_name='COSTER'>Coster - £7.53 (six pack)</option>
    <option class="op3" value="5" item_name='CLOCK'>Clock  - £5.00</option>
</select>
<input type='button' value="Go!" id='bu' />

JQuery

$('#bu').click(function() {
    alert($('.p1add1').attr('item_name'));
});

JSfiddle - http://jsfiddle.net/LYv2W/

【问题讨论】:

标签: javascript jquery html


【解决方案1】:
$('#bu').click(function() {
    alert($('.p1add1').children('option:selected').attr('item_name'));
});

http://jsfiddle.net/LYv2W/1/

【讨论】:

    【解决方案2】:

    简单地说:

    alert($('.p1add1 :selected').attr("item_name"));
    

    Fiddle

    【讨论】:

      【解决方案3】:

      假设您想要来自所选&lt;option&gt; 的属性:

      $('#bu').click(function() {
          alert($('.p1add1 option:selected').attr('item_name'));
      });
      

      JS Fiddle demo.

      如果你想获得所有属性:

      $('#bu').click(function() {
          alert($('.p1add1 option').map(function(){
              return this.getAttribute('item_name');
          }).get().join(', '));
      });
      

      JS Fiddle demo.

      如果您想使用自定义属性,并且希望您的文档进行验证(假设您使用的是 html 5),我强烈建议您使用 data-* 属性:

      <select class="p1add1">
          <option class="op1" value="3.74" data-item_name='BOWL'>Bowl   - £3.74</option>
          <option class="op2" value="7.53" data-item_name='COSTER'>Coster - £7.53 (six pack)</option>
          <option class="op3" value="5" data-item_name='CLOCK'>Clock  - £5.00</option>
      </select>
      <input type='button' value="Go!" id='bu' />
      

      使用 jQuery:

      $('#bu').click(function() {
          alert($('.p1add1 option:selected').data('item_name'));
      });
      

      JS Fiddle demo.

      参考资料:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-25
        相关资源
        最近更新 更多