gpt4 book ai didi

javascript - 在函数 jquery 中调用 data 属性

转载 作者:行者123 更新时间:2023-11-28 17:58:30 25 4
gpt4 key购买 nike

我有一些像这样的下拉列表:

<select name="qty" class="mb10" onchange="test()" data-plan-type="offer" data-plan-id="7395" data-plan-day="2210009">
<option value="0">0 rooms</option>
<option value="1">1 rooms</option>
<option value="2">2 rooms</option>
<option value="3">3 rooms</option>
<option value="4">4 rooms</option>
</select>

这是我用 onchange 调用的函数事件:

function test()
{
var this_plan_type = $(this).data('plan-type');
var this_plan_id = $(this).data('plan-id');
var this_plan_day = $(this).data('plan-day');

alert(this_plan_type);
}

问题出在 onchange事件我无法在我的 <select> 中调用数据属性 。我如何在函数内调用该数据属性?

最佳答案

您可以使用.bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value,

<select name="qty" class="mb10" onchange="test.bind(this)()" data-plan-type="offer" data-plan-id="7395" data-plan-day="2210009">
</select>

function test() {
var this_plan_type = $(this).data('plan-type');
var this_plan_id = $(this).data('plan-id');
var this_plan_day = $(this).data('plan-day');
console.clear();
console.log(this_plan_type, this_plan_id, this_plan_day);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="qty" class="mb10" onchange="test.bind(this)()" data-plan-type="offer" data-plan-id="7395" data-plan-day="2210009">
<option value="0">0 rooms</option>
<option value="1">1 rooms</option>
<option value="2">2 rooms</option>
<option value="3">3 rooms</option>
<option value="4">4 rooms</option>
</select>

关于javascript - 在函数 jquery 中调用 data 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com