javascript - 为什么该功能仅在第二次单击时起作用?

标签 javascript jquery

我正在尝试通过表单提交数据,当单击提交按钮时,我希望某些图像随着 style.display = 'none'; 消失。目前,我必须单击按钮两次才能使图像消失。有没有办法在第一次点击时执行此操作?

HTML:

<form action="/create_post/" method="POST" id="post-form">
    <div class="col-sm-4" id="toprow">
        <h4 style="font-family:verdana"> Models </h4>
        <img src='{% static 'images/USAcomplete2.png' %}' class="img-responsive thumbnail" id='gbimg' >
        <div class="btn-toolbar">
            <button type="submit" name="model" value="test" class="btn btn-default">test</button>
            <button type="submit" name="model" value="test2" class="btn btn-default">test2</button>
            <button type="submit" name="model" value="test3" class="btn btn-default">test3</button>
        </div>
    </div>
</form>

JS:

$('#post-form').on('submit', function(event) {
    event.preventDefault();
    console.log("form submitted!")
    create_post();
});

function create_post() {
    console.log("create post is working!");
    $("button").click(function() {
        var cbtn = $(this);
        var btnval = cbtn.val();
        console.log(btnval);
        document.getElementById('gbimg').style.display = 'none';
    });

    //$.ajax({
    //    url : "create_post/",
    //    type : "POST",
    //    data : { model : 
};

最佳答案

如果您的<button>执行submit对于表单的函数,您应该在提交表单时消失按钮,而不是在 create_post() 中添加单击处理程序方法。所以:

$('#post-form').on('submit', function(event) {
    event.preventDefault();
    console.log("form submitted!");

    var cbtn = $("button");
    var btnval = cbtn.val();
    console.log(btnval);
    document.getElementById('gbimg').style.display = 'none';

    create_post();
});

function create_post() {
    console.log("create post is working!");

    //$.ajax({
    //    url : "create_post/",
    //    type : "POST",
    //    data : { model : 
};

关于javascript - 为什么该功能仅在第二次单击时起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30919639/

相关文章:

javascript - 从子域引用 css 和 js 文件

javascript - 将击键事件保存到电子表格+计时

从 google CDN 使用 Jquery UI 日期选择器时很难看

php - 文件未在 ajax php mysql 中上传

javascript - 将多个 div 作为一个滑动到一侧

javascript - 使用 Javascript 选择特定单词?

javascript - 是否可以仅使用 JavaScript 而无需使用 HTML 将动态链接插入到电子邮件中? (使用Google脚本发送电子邮件)

javascript - 如何将项目从一个桶移动到另一个 - DragulaJS-Angular

javascript - jquery ajax 调用 "metho"而不是 "method"?

javascript - 为什么在滚动元素中使用 offset().top 和 scrollTop() 时我的尺寸没有按预期返回?