【问题标题】:jQuery on() not working on element inside disabled fieldsetjQuery on() 不适用于禁用字段集中的元素
【发布时间】:2020-05-22 18:45:38
【问题描述】:
<form>
  <fieldset disabled='disabled'>
    <input type='text' name='text' value='not to be edited' />
    <a href='#' class='editbutton'>click me</a>
  </fieldset>
</form>

jQuery 不工作:

$("body").on("click", ".editbutton", function(e) {
  e.preventDefault();
  console.log("hello");
});

jQuery 工作:

$(".editbutton").on("click", function(e) {
  e.preventDefault();
  console.log("hello");
});

所以,当你以 $("body") 为起点时,jQuery 不会捕捉到点击编辑按钮的事件,因为 fieldset 被禁用。

如果你以 $(".editbutton") 作为起点,jQuery 可以工作,尽管 fieldset 仍然被禁用。

这是预期的行为吗?是否有解决方法?我无法使用有效的解决方案,因为表单是动态创建的。

【问题讨论】:

  • 请在您的问题中创建一个小提琴,我们可以重现您的问题。您发布的代码完全有效。

标签: jquery click dynamically-generated fieldset


【解决方案1】:

您的代码完全有效,因此必须有额外的 JS 搞砸了您的逻辑。

$('.js-button').on('click', function() {
  $('.js-copy').eq(0).clone().appendTo('body');
});


$("body").on("click", ".editbutton", function(e) {
  e.preventDefault();
  console.log("hello");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="js-button"> copy form </button>
<form class="js-copy">
  <fieldset disabled='disabled'>
    <input type='text' name='text' value='not to be edited' />
    <a href='#' class='editbutton'>click me</a>
  </fieldset>
</form>

【讨论】:

  • 不,没有其他 JS 搞砸了,我只用上面的代码尝试了一个简单的设置。我注意到它也不适用于静态表单,所以我编辑了我的问题。因为我的表单是动态创建的,所以我不能使用工作示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 2015-12-18
相关资源
最近更新 更多