首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >怎样才能使这个jquery函数更简洁?

怎样才能使这个jquery函数更简洁?
EN

Stack Overflow用户
提问于 2011-02-05 07:40:11
回答 1查看 248关注 0票数 1

我在我的asp.net项目中的一个公共javascript文件中有这段代码。

jQuery-Lint每当我将鼠标悬停在受此函数影响的按钮上时,都会返回“您已多次使用同一选择器”。

代码语言:javascript
复制
//turns all the buttons into jqueryUI buttons
//#mainBody is on the master page, #childBody is on the modal page.
$("#mainBody button, #mainBody input:submit, #mainBody input:button, #childBody button, #childBody input:submit, #childBody input:button").livequery(function () {
    $(this).button().each(function (index) {
                            $(this).ajaxStart(function () {
                                    $.data(this, "old_button_val", $(this).val());
                                    $.data(this, "old_button_disabled", $(this).button("option", "disabled"));
                                    $(this).button("option", "disabled", true).val("Wait...");
                                }).ajaxStop(function () {
                                    $(this).val($.data(this, "old_button_val")).button("option", "disabled", $.data(this, "old_button_disabled"));
                                }).ajaxError(function () {
                                    $(this).val($.data(this, "old_button_val")).button("option", "disabled", $.data(this, "old_button_disabled"));
                                });
                        });
});

类似的问题也被问到了here

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-05 08:40:47

代码语言:javascript
复制
// Might be a good idea now to add a class to these element
// instead of using a long selector like this
// Additionally, :button already includes <button> elements
var selector = "#mainBody input:submit, #mainBody input:button, #childBody input:submit, #childBody input:button";

$(selector).livequery(function() {
    // Store a copy of $(this), which we'll reuse... and reuse... and reuse
    var t = $(this);

    // Create the callback function shared berween
    // ajaxStop and ajaxError
    function ajaxCallback () {
        t.button('option', {
             label: t.data("old_button_val"),
             disabled: t.data('old_button_disabled')
         });
    }

    t.button()
        .ajaxStart(function() {
            // Use $.fn.data instead of $.data
            t.data({
                // Using 'label' instead of 'val'
                // because <button> elements do not have 'value's
                "old_button_val", t.button('option', 'label'),
                "old_button_disabled": t.button("option", "disabled")
            }).button('option', {
                disabled: true,
                label: 'Wait...'
            });
        }).ajaxStop(ajaxCallback).ajaxError(ajaxCallback);
    });
});

免责声明:未经测试,因此不能保证正常工作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4903994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档