【问题标题】:Correct way to trigger radio button handler with jQuery使用 jQuery 触发单选按钮处理程序的正确方法
【发布时间】:2021-10-15 03:57:36
【问题描述】:

我有两个单选按钮。根据选中哪个,我想在页面上显示或隐藏<div>。所以我创建了这个处理程序。

$(function () {
    $('input[name="Search.LatestOnly"]').on('change', function () {
        if ($(this).val() == 'true')
            $('#date-section').hide(400);
        else
            $('#date-section').show(400);
    });
});

这很好用。但是我想在页面加载时将<div> 可见性设置为正确的状态,所以我添加了这一行:

$('input[name="Search.LatestOnly"]:checked').trigger();

这会产生对我没有意义的运行时错误。

jQuery.Deferred 异常:无法将未定义或空值转换为对象类型错误:无法将未定义或空值转换为对象 在 hasOwnProperty () 在 Object.trigger (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:70619) 在 HTMLInputElement。 (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:72108) 在 Function.each (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:2976) 在 S.fn.init.each (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:1454) 在 S.fn.init.trigger (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:72084) 在 HTML 文档。 (https://localhost:44377/Data/Search:206:58) 在 e (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:30005) 在 t (https://localhost:44377/lib/jquery/dist/jquery.min.js:2:30307) 未定义 S.Deferred.exceptionHook@jquery.min.js:2 t@jquery.min.js:2 设置超时(异步) (匿名)@ jquery.min.js:2 c@jquery.min.js:2 fireWith@jquery.min.js:2 开火@jquery.min.js:2 c@jquery.min.js:2 fireWith@jquery.min.js:2 准备好@jquery.min.js:2 B@jquery.min.js:2 jquery.min.js:2

未捕获的类型错误:无法将未定义或 null 转换为对象 在 hasOwnProperty () 在 Object.trigger (jquery.min.js:2) 在 HTMLInputElement。 (jquery.min.js:2) 在 Function.each (jquery.min.js:2) 在 S.fn.init.each (jquery.min.js:2) 在 S.fn.init.trigger (jquery.min.js:2) 在 HTML 文档。 (搜索:206) 在 e (jquery.min.js:2) 在 t (jquery.min.js:2)

谁能告诉我如何初始化我的 HTML,以便在页面加载后隐藏或显示 <div>

【问题讨论】:

  • 也许$('input[name="Search.LatestOnly"]:checked').trigger(); 执行得太快了?你能编辑html和css,还是只编辑js?
  • @asyncawait:我可以编辑 HTML。但是我把这段代码放在$(function() { ... }); 中,所以应该可以使用了。
  • 你能在触发元素之前记录它吗?那可以排除。我建议使用 checked html 属性作为初始状态,或者使用 css 使元素可见,稍后由 js 更改,或者由 js 立即更改为 .show
  • @asyncawait:我不知道你所说的记录元素是什么意思。我可以用 CSS 隐藏它,但是如果它应该显示它就会处于错误的状态。
  • 当我说“记录元素”时,我的意思是,console.log($('input[name="Search.LatestOnly"]:checked')) 在您的代码中出现错误之前可以在控制台中查看结果。

标签: javascript html jquery


【解决方案1】:

我太傻了。我忘了包括活动的名称。

$('input[name="Search.LatestOnly"]:checked').trigger('change');

多亏了一个完全没有帮助的错误消息,我在一个非常愚蠢的错误上浪费了很多时间。

【讨论】:

    【解决方案2】:

    这是一个连接到无线电输入的显示/隐藏的工作示例,它检查当前检查的值并立即运行,并添加事件侦听器。希望这为您自己的项目增加了一些视角。不幸的是,如果无法重现错误,就很难给出更具体的建议。我总是很乐意将您的项目与此答案分开查看。

    我做了一件厚颜无耻的小事,我让收音机的价值成为所需的方法,只是为了减少我通常必须编写条件来处理理解价值的步骤。

    $(() => {
      const content = $("div");
      const shown = $("input[name='test']:checked").val();
      const handleShow = (method, t = 200) => content[method](t);
      handleShow(shown, 0);
      $("input").on("change", function () {
        const shown = $(this).val();
        handleShow(shown);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      conditional content
    </div>
    <label> Show
      <input type="radio" name="test" value="show" checked>
    </label>
    <label> Hide
      <input type="radio" name="test" value="hide">
    </label>

    【讨论】:

    • 我不确定我是否理解你在那里用 handleShow 做什么。我希望避免“厚颜无耻的小事”。这就是为什么我不明白为什么 trigger() 不能工作。
    【解决方案3】:

    我想我也会包含一个在 vanilla javascript 中实现此目标的示例,作为其他任何偶然发现该问题的人的资源。

    在回答这个问题时要记住两件事,css 中 1rem 的最大高度不适用于所有容器。您可以动态设置最大高度,或者使用不可能高的东西(这会影响动画)

    这不会在初始启动时检查“已检查”状态,它假定它在启动时始终具有相同的状态。

    (() => {
      const $ = str => [...document.querySelectorAll(str)];
      const content = $("div")[0];
      const radios = $("input[name='test']");
      radios.forEach(radio => {
        radio.addEventListener("input", e => {
          const val = e.target.value;
          if (val === "show") content.classList.remove("hidden");
            else content.classList.add("hidden");
        });
      });
    })();
    div {
      max-height: 1rem;
      transition: max-height .2s;
      overflow: hidden;
    }
    
    .hidden {
      max-height: 0;
    }
    <div>
      conditional content
    </div>
    <label> Show
      <input type="radio" name="test" value="show" checked>
    </label>
    <label> Hide
      <input type="radio" name="test" value="hide">
    </label>

    【讨论】:

    • 假设“初始启动”状态正是我需要避免的。而且我不明白为什么不能使用 trigger()。
    猜你喜欢
    • 2013-07-26
    • 2019-07-24
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    相关资源
    最近更新 更多