为什么功能仅在第二次点击时起作用? [英] Why does function only work on second click?

查看:72
本文介绍了为什么功能仅在第二次点击时起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to submit data through a form and when the submit button is click I want certain images to disappear with style.display = 'none';. Currently, I have to click the button twice before images disappear. Is there a way to do this on first click?

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()方法中的点击处理程序。所以:

If your <button> executes the submit function for the form, you should just disappear the button on submitting of the form instead of adding the click handler in the create_post() method. So:

$('#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 : 
};

这篇关于为什么功能仅在第二次点击时起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆