简体   繁体   English

如何将 select 选项中的数据目标属性应用于按钮?

[英]How to apply data-target attribute from select option to a button?

How can I grab the data-target attribute from the options and apply that data-target as a data-target to the button after the selection is made?如何从选项中获取数据目标属性,并在选择后将该数据目标作为数据目标应用于按钮?

HTML: HTML:

<div>
<select id="selectID">
                <option value="option1" data-target="data1">Select</option>
                <option value="option1" data-target="data1">Select</option>
            </select>
            <button id="selBtn" data-target="">Button</button>
</div>

Javascript: Javascript:

 $("#selectID").change(function () {
                            var prop = $(this).data("data-target");
                            $("#selBtn").attr("data-target", prop);
                        });

Replace second line with var prop = $("#selectID option:selected").data("target");var prop = $("#selectID option:selected").data("target");替换第二行. .

SIDE NOTE: It's a good practice to have a default option with value 0 (or default).旁注:最好使用值为 0(或默认值)的默认选项。 So the option1 is not selected automatically.所以 option1 不会自动选择。

 $("#selectID").change(function () { var prop = $("#selectID option:selected").data("target"); $("#selBtn").attr("data-target", prop); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <select id="selectID"> <option value="0" data-target="data1">Please Select</option> <option value="option1" data-target="data1">Select 1</option> <option value="option2" data-target="data2">Select 2</option> </select> <button id="selBtn" data-target="">Button</button> </div>

$(this).data("data-target")

With this you are selecting #selectID reference.有了this ,您正在选择#selectID 参考。

Try this:尝试这个:

 $("#selectID").change(function() {
  console.log($(this).find(':selected').data('target'));

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM