函数名称为HTML属性

时间:2010-12-16 17:43:16

标签: jquery html ajax

我知道函数可以存储在特定事件的html属性上(例如onmouseover),但是任何属性都可以引用函数或只是特殊属性吗?

我想基于表单属性自动连接ajax成功和失败回调[例如的onSuccess = “警报( 'whoohoo');”和onfail =“alert('你吮吸');”]。这样的事情是可能的,还是我必须将函数存储在已知事件上并在失败或成功时触发事件?


我想与SO分享结果代码以获得社区的利益。遗憾的是,我不能使用data- *作为属性名称,因为' - '不是属性名称的有效字符,而表单是使用MVC和匿名类型创建的。

// provide the ability to manually setup a form for ajax processing.
// target are the forms to be wired
// success is the callback function
function AjaxifyForms(target, success, fail) {
    $(target).each(function() {       // Wierdness if each isn't used with validation
        $(this).validate({
            submitHandler: function(form) {
                $.ajax({                                                           //create an AJAX request
                    type: "POST",                                                  //use POST (we could also load this from the form if wanted to)
                    url: $(form).attr("action"),                       //get the URL from the form
                    data: $(form).serialize(),
                    datatype: "json",
                    success: function(data) {
                        if (success != undefined && success != null) success(data);
                        else if ($(form).attr("ajaxSuccssCallback") != undefined && $(form).attr("ajaxSuccssCallback") != null)
                            window[$(form).attr("ajaxSuccssCallback")](data);
                        else alert("Success");
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if (faile != undefined && fail != null) fail(data);
                        else if ($(form).attr("ajaxFailCallback") != undefined && $(form).attr("ajaxFailCallback") != null)
                            window[$(form).attr("ajaxFailCallback")](data);
                        else alert("Epic Fail");
                    }
                });
                return false;                            //don't forget to cancel the event so we don't submit the page!
            }
        });
    });
}

2 个答案:

答案 0 :(得分:3)

更好的方法是使用HTML5中的data-*属性,并且只存储函数名称,而不是实际的可执行JavaScript代码。例如,

<form id="MyForm" data-success-callback="woohoo" data-failure-callback="suck" />

然后通过

获取对这些功能的引用
var successFunc = window[$("#MyForm").attr("data-success-callback")];
var failureFunc = window[$("#MyForm").attr("data-failure-callback")];

只有当它们具有全局功能时才有效;否则你需要做一些有点棘手的事情(比如拆分.然后使用索引表示法)来获取函数引用。

答案 1 :(得分:1)

HTML 5规范包含所有valid event handler attributes

的列表

我认为处理自定义事件(使用jQuery)的最佳方法是在脚本中绑定它们,并手动触发它们。

实施例

$('#myForm').bind('prefix-success', mySuccessFunction)
  .bind('prefix-fail', myFailFunction);

然后当它失败或成功时,你会触发正确的功能

if (success) $('#myForm').trigger('prefix-success');
else if (fail) $('#myForm').trigger('prefix-fail');

当然,这是对手头问题的过分简化。您将要创建一种调用/绑定事件的通用方法。

我建议使用事件前缀,以便您可以确定您的事件不会在以后的HTML规范中被覆盖。

编辑添加:
我忘了提及为什么保持脚本中的功能是最好的:

HTML用于语义标记(模型)。 CSS用于样式(视图)。 JavaScript用于交互(控制器)。将控制细节保留在控制器中,这样就不会使模型混乱。