微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在使用 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 举报,一经查实,本站将立刻删除。