【问题标题】:Passing variable to jQuery plugin parameter将变量传递给 jQuery 插件参数
【发布时间】:2016-11-08 22:04:16
【问题描述】:

我在弄清楚如何将变量传递给ajaxForm() 函数的参数时遇到了问题。单击 jQuery 中的表单按钮后,我从隐藏的表单字段获取 templatedir 路径(这很好用),我可以将它传递给其他函数,但不能传递给 ajaxForm() 参数:

    var templatedir;

    // Get variable of templatedir
    $('form#contact input[type="submit"]').on('click',function(){
        templatedir = $('input[name=templatedir]').fieldValue();   
    });

    // Validate Form
    function validateform(formData, jqForm, options) {         
        ...
        // IF I CALL TEMPLATEDIR HERE IT WORKS
    }   

    // Send to PHPMailer
    $("form#contact").ajaxForm({
        url: templatedir, // IT DOESNT WORK HERE
        type: 'post', 
        beforeSubmit: validateform,
        target: '#msg',
        clearForm: true
    });

如您所见,我尝试了此答案 (How do i pass variables between functions in javascript) 中的解决方案,但它不起作用。

【问题讨论】:

  • 嗯...是这样吗? templatedir = $('input[name=templatedir]').fieldValue();
  • 是的,这是正确的,我可以将结果传递给console.log,它工作得很好。

标签: jquery ajaxform


【解决方案1】:

您的变量 templatedir 未定义。

你应该在点击事件中调用ajaxForm()

$('form#contact input[type="submit"]').on('click',function(event) {
    event.preventDefault();

    // Send to PHPMailer
    $("form#contact").ajaxForm({
        url: $('input[name=templatedir]').fieldValue(),
        type: 'post', 
        beforeSubmit: validateform,
        target: '#msg',
        clearForm: true
    });
});

【讨论】:

    【解决方案2】:

    兴趣点是:

    • 在设置之前不能使用 templatedir 变量
    • templatedir = $('input[name=templatedir]').fieldValue(); 更改为

      templatedir = $('input[name=templatedir]').val();

    • 删除url: templatedir, // IT DOESNT WORK HERE并将其设置在validateform中:在表单提交之前

    我的sn-p:

    var templatedir;
    
    $(function () {
      $('form#contact input[type="submit"]').on('click', function(){
        templatedir = $('input[name=templatedir]').val();
      });
      function validateform(formData, jqForm, options) {
        // because you now are in the beforesubmit event
        // you can change the url.....
        options.url = templatedir;
      }
    
      $("form#contact").ajaxForm({
        type: 'post',
        beforeSubmit: validateform,
        target: '#msg',
        clearForm: true
      });
    });
    <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
    <script src="https://malsup.github.io/jquery.form.js"></script>
    
    <form id="contact" action="www.google.com" method="post">
        templatedir: <input type="text" name="templatedir"/>
        <input type="submit" value="Submit Comment" />
    </form>
    <div id="msg"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2014-04-08
      • 2014-12-02
      • 2012-03-02
      相关资源
      最近更新 更多