“对象不支持此属性或方法”在函数内部调用方法时出错

问题描述

我正在使用 selected.js 库。我有几个下拉列表被禁用,并希望它们在调用函数时可用。

<script>
...
    $('.chzn-select').each(function () {
        $(this).chosen();
    });

    function edit()
    {
        $('.chzn-select').each(function () {
            $(this).removeAttr("disabled");
            $(this).trigger("chosen:updated");
        });
    }
...
</script>

然而,即使调用 edit() 函数,下拉列表也不会改变,因为“chosen:updated”事件没有被触发。当我向编辑函数添加类似 $(this).chosen("destroy") 的内容时,我收到“对象不支持属性方法错误。这让我觉得该函数不能使用 selected.js 库?此外,代码在不在函数中时也能工作:

<script>
...
    $('.chzn-select').each(function () {
        $(this).chosen();
    });

    $('.chzn-select').each(function () {
        $(this).removeAttr("disabled");
        $(this).trigger("chosen:updated");
    });
...
</script>

编辑 示例代码段 - 需要更新

$(".chzn-select").chosen();

// No need to loop to activate chosen
//$('.chzn-select').each(function () {
//    $(this).chosen();
//});

function edit()
{
    $('.chzn-select').each(function () {
        $(this).removeAttr("disabled");
        $(this).trigger("chosen:updated");
    });
}

$("#btn").click(()=>edit());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css" />

<select class='chzn-select' disabled>
  <option>Option 1</option>
  <option>Option 2</option>
</select>

<select class='chzn-select' disabled>
  <option>Option 3</option>
  <option>Option 4</option>
</select>

<button type='button' id='btn'>enable</button>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)