简体   繁体   English

使用传递的数据属性调用函数

[英]Call function using passed data attributes

I have a form like: 我有一个像这样的表格:

<form data-controller="Posts" data-method="admin_add">

And then I want to call a function based on these passed data attributes when the form is submitted. 然后,我想在提交表单时基于这些传递的数据属性调用一个函数。

$(document).on('submit', 'form', function(e){

    e.preventDefault(); // there is no server so nothing to submit to

    var formData = $(this).serialize();

    var controller = $(this).attr('data-controller');
    var method = $(this).attr('data-method');
    // I use .attr instead of .data because .data is funny sometimes

    var fnString = controller + '.' + method;
    var fn = window[fnString];

    if (typeof fn === "function") fn(formData);

});

This is based on what I've read here: http://www.sitepoint.com/call-javascript-function-string-without-using-eval/ 这是基于我在这里阅读的内容: http//www.sitepoint.com/call-javascript-function-string-without-using-eval/

And it should of called: 它应该称为:

Posts.admin_add(formData);

But it doesn't call the function... and if I remove the if statement then I get an error that it's not a function... Any ideas? 但是它不调用函数...如果删除if语句,则会收到错误消息,它不是函数...有什么想法吗?

Remember, you are using square brackets to avoid using eval : 请记住,您使用方括号来避免使用eval

var fn = window[controller][method];
fn(formData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM