【问题标题】:jQuery events don't occur after I change button class更改按钮类后不会发生 jQuery 事件
【发布时间】:2019-05-01 09:20:41
【问题描述】:

我试图在单击时更改按钮的类,以便在下次单击时执行不同的操作。 (我不想使用切换)

更改类后,下次单击这些按钮时,即使类已更改,也不会发生任何事情。谁能帮帮我?我刚开始接触jQuery,所以我不知道很多高级机制。

 $(".showcontactbutton").click(function(){
    $("#contactform").show();
    //$(this).attr('class', 'hidecontactbutton');
    $(this).removeClass('showcontactbutton').addClass('hidecontactbutton');
    $(this).text("Hide Contact Form");
    //html("<button id='hidecontactbutton'>Hide Contact Form</button>");

});

$(".hidecontactbutton").click(function(){
    alert("Works:");
    $("#contactform").hide();
    //$(this).attr('id', 'showcontactbutton');
    $(this).removeClass('hidecontactbutton').addClass('showcontactbutton');
    $(this).text("Contact Us");
});

【问题讨论】:

    标签: jquery html css web


    【解决方案1】:

    元素上的事件在加载时绑定,因此当您更改元素绑定的类时,事件会丢失。将事件绑定到您不更改的类或将事件绑定到文档。

    $(document).on("click", ".showcontactbutton" , function() {
        ...
    ]);
    

    有关更多信息,请搜索动态元素上的绑定。

    【讨论】:

      【解决方案2】:

      如果&lt;button&gt; 没有type 属性,则默认为type='"submit"。如果说&lt;button&gt; 不在&lt;form&gt; 中,这并不明显,但如果它在&lt;form&gt; 中,那么每次点击都会启动提交事件的默认行为:

      • 收集具有嵌套在&lt;form&gt; 中的[name] 属性的所有表单控件的所有值。

      • 将所有值发送到action 属性指示的服务器。

      • 重置&lt;form&gt;

      所以将type="button" 添加到&lt;button&gt;

      <button id='hidecontactbutton' type="button">...</button>
      

      至于切换#contact 的状态,您应该定位按钮的#id,然后切换类。您是否打算将类放在按钮上而不是 #contact 上? $(this) 指的是单击的任何内容(在此上下文中应该是按钮)。

      $('#hideShow').on('click', hideShow);
      
      function hideShow(e) {
        if ($(this).hasClass('hide')) {
          $(this).removeClass('hide').addClass('show').text('Hide Contact Form');
          $('#contact').show();
        } else {
          $(this).removeClass('show').addClass('hide').text('Contact Us');
          $('#contact').hide();
        }
      };
      button {
        display: inline-block;
        width: 18ch;
        cursor: pointer;
      }
      
      #contact {
        display: none;
        width: fit-content;
      }
      
      [type=submit] {
        float: right
      }
      <button id='hideShow' class='hide' type='button'>Contact Us</button>
      <form>
        <fieldset id='contact'>
          <legend>Contact Us</legend>
          <label for='email'>Email: </label><br>
          <input type='email'><br>
          <label for='email'>Comment: </label><br>
          <textarea></textarea><br>
          <button type='submit'>Send</button>
        </fieldset>
      </form>
      
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

      【讨论】:

      • 感谢您的回答!我遇到问题的按钮在表单之外。
      • 更新了 HTML,它可以在表单内部或外部工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      相关资源
      最近更新 更多