jquery - 为什么我无法在单击选项时获取 jquery 中选定选项的值?
问题描述
我有以下带有选项的选择菜单。
<select name="assigneeSelect" id="{{this.commonID}}" class="custom-select sources" key="{{this.id}}" placeholder="{{this.assignee}}">
<option value="5f4a31eb75d1ab1668d11765">Charlotte Miles</option>
<option value="d91c3fb7642c6d415880301e1c776df4">Sulekha Yadav</option>
<option value="5f4d49636dba221200f2cc1f">Adele Armstrong</option>
</select>
所以在 jQuery 中,我用更多的类来包装这段代码,如下所示,因为我在同一页面上有多个选择菜单选项。
$(".custom-select").each(function() {
var classes = $(this).attr("class"),
id = $(this).attr("id"),
name = $(this).attr("name");
var template = '<div class="' + classes + '">';
template += '<span class="custom-select-trigger">' + $(this).attr("placeholder") + '</span>';
template += '<div class="custom-options">';
$(this).find("option").each(function() {
template += '<span class="custom-option ' + $(this).attr("class") + '" data-value="' + $(this).attr("value") + '">' + $(this).html() + '</span>';
});
template += '</div></div>';
$(this).wrap('<div class="custom-select-wrapper"></div>');
$(this).hide();
$(this).after(template);
});
$(".custom-option:first-of-type").hover(function() {
$(this).parents(".custom-options").addClass("option-hover");
}, function() {
$(this).parents(".custom-options").removeClass("option-hover");
});
$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});
因此,我在选择菜单中单击选项时检索选定的文本。我不想在所选菜单的更改上检索它,因为我必须在单击时调用一个 AJAX Get。表示从选择下拉列表中选择其中一个选项后。
$(".custom-option").on("click", function() {
**var text = $(this).text();**
**var val = $(this).val();**
alert("id ="+id+" text = "+text+" val ="+val);
})
但是在 val 中,虽然我得到了文本,但我没有得到选项的价值。
解决方案
You create your custom-option
using:
<span class="custom-option ' + $(this).attr("class") + '" data-value="' + $(this).attr("value") + '">' + $(this).html() + '</span>'
this doesn't have a "value" that jquery can extract using .val()
, but it does have data-value=..
.
You can get the data-value using
var val = $(this).data("value");
推荐阅读
- java - 如何实现 Guava 缓存来存储和获取不同类型的对象?
- angular - 角 | 如何使用 ng-template 或任何方法将 ng-content/child 内容置于组件之外
- c# - 如何将带小数点的字符串转换为带小数点逗号的双精度?
- angular - Primeng - 如何在多选/下拉列表的标题中添加一个按钮?
- vb.net - 想要将文本框中的行添加到列表框中,如果它包含单词中的单词
- powershell - 在 PowerShell 中管理基于批处理的服务器
- dockerfile - ECS Fargate 日志文件位置
- python - StreamHandler 的实例默认使用 sys.stderr 是什么意思?
- r - 更改数据框格式并使用复制作为列执行方差分析
- vba - 使用 VBA 处理在 VSTO 加载项中定义的功能区控件