【问题标题】:can not get customized attribute value when using ajax in select2在select2中使用ajax时无法获取自定义属性值
【发布时间】:2020-08-29 02:57:05
【问题描述】:

我正在使用 ASP.NET

我有一个使用 select2 的下拉菜单,并且在选择某些内容时使用 ajax 调用具有两个参数的(apicontroller)操作。

动作:

public class MyController: ApiController
{
    [HttpGet]
    public string Helper(string para0, string para1, string para2) { return something;}
}

html:

<select id="selectCase">
    <option>Select a Case</option>
    <option value="abc" data-para1="1" data-para2="2"> "abc" </option>
    <option value="def" data-para1="1" data-para2="2"> "abc" </option>
</select>

js函数:

$('#selectCase').on('select2:select', function() {
        $.ajax({
            type: "GET",
            url: "/api/MyController/Helper?para0=" + $(this).val() + "&para1=" + $(this).attr("data-para1") + "&para2=" + $(this).attr("data-para1"),

但是当它运行时,只有 $(this).val() 得到正确的值,$(this).attr("data-para1" 和 $(this).attr("data-para1" 都是未定义的. 也试过用$(this).data("para1"),还是不行。

谢谢,


我实际上跳过了我在 html 中使用 optgroup 的部分,不确定这是否有什么不同

<select id="selectCase">
    <option></option>
    <optgroup label="0">
        <option value="abc" data-para1="1" data-para2="2"> "abc" </option>
    </optgroup>
    <optgroup label="0">
        <option value="def" data-para1="1" data-para2="2"> "abc" </option>
    </optgroup>
</select>

【问题讨论】:

    标签: javascript asp.net ajax asp.net-ajax jquery-select2


    【解决方案1】:

    您可以使用$(this).find('option:selected') 获取选定的选项,然后获取您在每个选项中定义的自定义属性。

    演示代码

    $('#selectCase').select2({
      width: '100%',
      placeholder: "Select an Option",
      allowClear: true
    });
    
    $('#selectCase').on('select2:select', function() {
      //getting selected option and then retrieve required data
      var $select = $(this).find('option:selected');
      console.log("para0=" + $select.val() + "&para1=" + $select.attr('data-para1') + "&para2=" + $select.attr('data-para2'));
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
    
    <select id="selectCase">
        <option></option>
        <optgroup label="0">
            <option value="abc" data-para1="1" data-para2="2"> "abc" </option>
        </optgroup>
        <optgroup label="0">
            <option value="def" data-para1="1" data-para2="2"> "abc" </option>
        </optgroup>
    </select>

    【讨论】:

    • 感谢您的帮助!!!虽然我仍然不确定....但我想知道这是否真的是由于我使用了我在原始问题陈述中跳过的 optgroup,我已经更新了它并尝试使用 $(this).children('optgroup:selected ').children('option:selected').attr("data-para1") 又一次不起作用......
    • 我已经更新了我的答案,你可以使用$(this).find('option:selected'),看看是否有效
    猜你喜欢
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2015-04-26
    • 2018-10-01
    • 2014-02-05
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多