【问题标题】:get data-* from different selects onchange从不同的选择中获取数据-* onchange
【发布时间】:2017-08-29 15:41:27
【问题描述】:

试图将 data-* 属性的值发送给函数。

我有两个不同的选择,我想将所选选项的 data-addr 值发送到函数并将其显示在#results div中。

我能够使用以下脚本使其与一个选择一起工作,但我希望我的脚本与多个选择一起工作并替换为最后选择的选项的 data-addr 值。

var test = $('#thefirstselect option:selected').data('addr');
$('#result').text(test);

这里是html

<div>
  <select class="form-control" id="thefirstselect" onchange="setaddress();">
    <option value="" data-addr="001">one</option>
    <option value="" data-addr="002">two</option>
    <option value="" data-addr="003">three</option>
  </select>
</div>

<div>
  <select class="form-control" id="thesecondselect" onchange="setaddress();">
    <option value="" data-addr="004">four</option>
    <option value="" data-addr="005">five</option>
    <option value="" data-addr="006">six</option>
  </select>
</div>

https://codepen.io/carlos27/pen/brQBGE

【问题讨论】:

  • $("select option:selected").each(function() { console.log($(this).data("addr")) });

标签: javascript jquery html


【解决方案1】:

使用$(this) 表示正在更改的选择,使用option:selected 选择已选择的选项。还要避免使用内联 JavaScript:

$('#thefirstselect, #thesecondselect').change(function() {
  var test = $(this).find('option:selected').data('addr');
  console.log(test);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <select class="form-control" id="thefirstselect">
    <option value="" data-addr="001">one</option>
    <option value="" data-addr="002">two</option>
    <option value="" data-addr="003">three</option>
  </select>
</div>

<div>
  <select class="form-control" id="thesecondselect">
    <option value="" data-addr="004">four</option>
    <option value="" data-addr="005">five</option>
    <option value="" data-addr="006">six</option>
  </select>
</div>

【讨论】:

    猜你喜欢
    • 2012-06-26
    • 2020-03-09
    • 1970-01-01
    • 2012-09-24
    • 2014-08-06
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多