jquery - 我正在尝试从选择中获取年份,但在 jquery 中未定义
问题描述
当我选择任何一年时,我试图从选择选项中获得一年,然后我在警报中变得不确定,请帮助我,谢谢。
html视图
<label for="opt11" class="option">Select Year</label>
@foreach($years as $year)
<input class="selectopt" name="test1" type="radio" id="opt{{$year->year}}">
<label for="opt{{$year->year}}" data-year="{{$year->year}}" class="option text-box year" data-maxlength=28>
<p>{{$year->year}}</p>
</label>
jQuery脚本
$('.selectopt').on('change', function() {
let year = $(this).data('year');
alert(year); getting unfined
});
解决方案
this
在您的更改处理程序中是单选按钮,而不是<label>
元素。
试试这个
let year = $(`label[for="${this.id}"]`).data("year")
甚至这个
$(this).next("label.option").data("year")
当您可以使用单选按钮时,我看不出有任何理由使用数据属性value
<input
class="selectopt"
name="test1"
type="radio"
id="opt{{ $year->year }}"
value="{{ $year->year }}"
>
$(".selectopt").on("change", function(e) {
const year = this.value
})
推荐阅读
- c - 用户输入的错误处理,直到输入正确
- javascript - JavaScript 确认框上的取消选项仅返回真条件
- android - 位图 - 避免在缩放期间在内存中进行不必要的加载
- emacs - 将转义序列从 tmux 传递到 gnu 屏幕
- c - 使用strtod后如何将double值转换为char数组?在 C 中
- sonata - 奏鸣曲分类捆绑路径问题
- python-3.x - 模仿操作系统调度程序的协程
- javascript - 反复从网页读取 javascript 输出
- autodesk-forge - 如何在查看器上设置浅色主题?
- angular - 成功将 Angular 应用程序部署到 heroku 后的 HTTP 404