为什么我无法在单击选项时获取 jquery 中所选选项的值?

Why i am unable to fetch the values of selected options in jquery on click of option?

我有以下 select 菜单和选项。

 <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 中,我用更多 类 包裹这段代码,如下所示,因为我在同一页面上有多个 select 菜单选项。

$(".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();
});

所以我在 select 菜单中单击选项来检索 selected 文本。我不想在更改 selected 菜单时检索它,因为我必须调用一个 AJAX 获取点击。表示在 select 从 select 下拉列表中选择其中一个选项后。

$(".custom-option").on("click", function() {


**var text = $(this).text();**
**var val = $(this).val();**

alert("id ="+id+" text = "+text+" val ="+val);

}) 

但是在 val 中,虽然我得到了文本,但我没有得到选项的值。

您创建 custom-option 使用:

<span class="custom-option ' + $(this).attr("class") + '" data-value="' + $(this).attr("value") + '">' + $(this).html() + '</span>'

这没有 jquery 可以使用 .val() 提取的“值”,但它确实有 data-value=...

您可以使用

获得data-value
var val = $(this).data("value");