javascript - 在 jQuery.extend() 中使用 $(this)

标签 javascript jquery forms object jquery-plugins

我正在使用jQuery form plugin ,并希望此插件在每个 form.ajaxify 上使用。所以我有这个:

$('form.ajaxify').ajaxForm(
    // the options
);

使用 HTML <form class="ajaxify" ...> ... </form> .

现在,我有一些我想始终传递的选项,例如 dataType:'json' 。除此之外,我希望能够在 form 中添加更多选项标签,像这样:

<form class="ajaxify" ... data-ajaxify-options='{"target":"#x"}'> ... </form>

根据the docs on .data() 这是有效的.

所以我想我会使用 jQuery.extend() 。我试着这样说:

$('.ajaxify').ajaxForm(
    jQuery.extend(
        {
            dataType: 'json'
        }, 
        $(this).data('ajaxify-options')
    )
);

但是,这不起作用:仅传递文字对象,而没有扩展任何内容。我这不起作用,因为 $(this)不再引用 form.ajaxify元素。它是否正确?通常可以存储 $(this)然而,在变量中,这意味着代码变得复杂,对吧?再也不可能在一根线上了。或者还有其他解决方案吗?

最佳答案

I suppose this doesn't work because $(this) doesn't refer anymore to the form.ajaxify element. Is this correct?

是的,尽管this从未引用过该元素。它仅在 jQuery 调用的回调函数内部执行操作,但是您使用它来构建 ajaxForm 调用的参数this 将引用任何 the this context currently refers to .

Normally one could store the $(this) in a variable, however, that would mean complicating the code, right?

您可以将 $('form.ajaxify') 存储在变量中,因为 $(this) 毫无意义,但确实需要这样做。不过,它并没有真正使代码“复杂化”:

var form = $('.ajaxify');
form.ajaxForm($.extend({
    dataType: 'json'
}, form.data('ajaxify-options')));

如果您想避免使用该变量,则需要重复选择器,这是一个不好的做法。

对于适用于选定集合中的多个表单的代码片段,您可以使用 .each()将该方法应用于可能具有不同选项的每个元素 - 在其回调中,您现在可以使用 this:

$('.ajaxify').each(function() {
    // caching $this=$(this) is possible as well, but not as necessary
    $(this).ajaxForm($.extend({
        dataType: 'json'
    }, $(this).data('ajaxify-options')));
});

关于javascript - 在 jQuery.extend() 中使用 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25630179/

相关文章:

javascript - 成功后弹出消息窗口并禁用“提交”按钮

javascript - 同时编辑多个 HTML 文本输入

Java Servlet : Send form data by email.(Netbeans)

jquery - 在输入字段中输入一定长度的文本后如何自动提交表单

javascript - 切换div应该先隐藏

javascript - 隐藏下拉菜单

javascript - Phonegap 全局化 API

javascript - new Array(7) 和 Array.apply(null, Array(7)) 的区别

javascript - Vue js 中 IE 11 中的参数无效

javascript - 如何在 sqlite3 db.get 和 db.all 中使用 async/await?