首页 > 解决方案 > .preventDefault() 不再正常运行

问题描述

我必须错过一些简单的东西。该脚本按预期运行,直到我添加了一个新元素来使用导航栏中的按钮切换输入框。现在表单将在提交时重定向。

预期的行为是,当输入提交时,它会在评论框下方显示为评论。

目前我的 .preventDefault(); 当我被重定向时,不再处理点击。我花了太多时间试图找出问题所在,并且需要对我更改或实施不正确的内容有所了解。

$(function () {

    //Toggle compose input box
    $(".compose").click(function () {
        event.preventDefault();
        $(".new").slideToggle("slow");
        textarea.focus()
    })

    //compose input to comment
    $('.Form').on('submit', function (event) {
        event.preventDefault();
        // 1. Grab the content of the form
        let formData = $('.Form').serialize();
        let entry = $('.textarea input').val();

        console.log(entry)
        if (entry === null || entry === '') {
            alert('text too short!')
        } if (entry.length > 140) {
            alert('text too long!')
        } else {
            // 2. Submit using ajax
            $.ajax('/comments', {
                method: 'POST',
                data: formData,
            }).then(function (success) {

                console.log('succesful')
                // 4. Make sure the new comments shows
                return $.ajax('/comments');
            }).then(renderComments());
        }
    });
});

html:

<main class="container">
  <section class="new">

    <form action='/comments' Method='POST' id="Form">
      <h2>Compose Comment</h2>
      <textarea id="textarea" name="text" onfocus='this.select()' placeholder="What are you humming about?"></textarea>
      <input class="submit" type="submit" value="Submit">
      <span class="counter">140</span>
    </form>
  </section>

标签: javascriptjqueryhtmlajax

解决方案


您的表单具有 id="Form",但您正在使用 jQuery 选择类。

即你需要:

//compose input to comment
$('#Form').on('submit', function(event) {
  event.preventDefault();
}

小心,序列化逻辑也在使用类,更新你的引用。


推荐阅读