【问题标题】:Getting Data Attributes on Dynamically Created Select Lists using Javascript使用 Javascript 获取动态创建的选择列表的数据属性
【发布时间】:2022-07-06 01:24:59
【问题描述】:

我在动态创建的选择列表上有一个 onchange 函数,它试图获取数据属性,但我得到一个“未定义”的值。

function changed_option(barcode,id,priceid,price){
  var barcode=barcode;
  var record=id;
  var change_action = ( $(this).find(':selected').data('change_action'));
  var change_amount = ( $(this).find(':selected').data('change_amount'));
  alert("Change Action: "+change_action);
  alert("Change Amount: "+change_action);
}

生成的HTML代码是:

<select onchange="changed_option('QKCLASS01NB','1282389738','price_QKCLASS01NB','125.00')"class="form-control col-md-10 center" id="1282389738" required="required" name="attributes[Payment Option]">
<option value="">---Select Option---</option><option data-change_action="0"data-change_amount="0.00">Full Price</option>
<option data-change_action="2"data-change_amount="20.00">Down Payment</option>
</select>

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript custom-data-attribute selectlist


    【解决方案1】:

    给你。

    function changed_option(barcode,id,priceid,price){
      var barcode=barcode;
      var record=id;
      var change_action = ( $('#'+id).find(':selected').data('change_action'));
      var change_amount = ( $('#'+id).find(':selected').data('change_amount'));
      alert("Change Action: "+change_action);
      alert("Change Amount: "+change_amount);
    }
    

    由于您使用的是 onchange 事件。这不会为您提供下拉列表的参考。您可以使用下拉列表的 id 来获取选择的值。

    【讨论】:

      【解决方案2】:

      您可以将this 传递给changed_option 以定位正确的元素。

      function changed_option(el, barcode,id,priceid,price){
        var barcode=barcode;
        var record=id;
        var change_action = ( $(el).find(':selected').data('change_action'));
        var change_amount = ( $(el).find(':selected').data('change_amount'));
        alert("Change Action: "+change_action);
        alert("Change Amount: "+change_amount);
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <select onchange="changed_option(this, 'QKCLASS01NB','1282389738','price_QKCLASS01NB','125.00')"class="form-control col-md-10 center" id="1282389738" required="required" name="attributes[Payment Option]">
      <option value="">---Select Option---</option><option data-change_action="0"data-change_amount="0.00">Full Price</option>
      <option data-change_action="2"data-change_amount="20.00">Down Payment</option>
      </select>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-05
        • 1970-01-01
        • 1970-01-01
        • 2019-02-06
        • 2018-04-07
        • 2023-03-03
        • 1970-01-01
        • 2017-12-26
        相关资源
        最近更新 更多