调用 .css() 后触发事件(保存当前样式)?

发布于 2025-01-02 09:51:51 字数 1264 浏览 3 评论 0原文

情况:我的 jQuery 插件允许我传递一个在返回对象(来自 ajax 调用)包含错误属性时要执行的函数。在该函数中,可以设置 css() 属性来突出显示失败。代码中的参数 isError 用于模拟这一点。

问题:当插件连续调用两次并且出错后成功时,样式当然没有改变,$(this).html("Success") 显示令人毛骨悚然的红色文本

问题:有没有办法在调用 .css() 后执行事件,从而保存当前样式以便稍后恢复(仅在成功时)?

<div id="container"></div>
<script>
      $('#container').attach({}, true);  // First call is error
      $('#container').attach({}, false); // Second call is success
</script>

这是我的插件(的一部分):

(function($) {
   $.fn.attach = function(options, isError) {

      var opt = $.extend({
         onError : function(message) { // Default function for errors
            this.html('Error: ' + message + '.').css('color', 'red');
        }
      }, options);

      // Loop each selection item
      this.each(function() {

         if(isError) // An error occurred, call opt.onError
         {
            opt.onError.call($(this), "Message");
            return true; // End of the current element process
         }

         $(this).html("Success"); // No errors, set success text

      });

   };
})(jQuery);

The situation: my jQuery plugin allows me to pass a function to be executed if returned object (from ajax call) contains an error property. In that function one can set css() properties to highlight the fail. In the code parameter isError is used to simulate this.

The problem: When the plugin is invoked two consecutive times and there is a success after an error, of course the style is unchanged and $(this).html("Success") shows a creepy red text.

The question: is there any way to execute an event after .css() is invoked thus saving the current style for restore it later (only on success)?

<div id="container"></div>
<script>
      $('#container').attach({}, true);  // First call is error
      $('#container').attach({}, false); // Second call is success
</script>

This is (part of) my plugin:

(function($) {
   $.fn.attach = function(options, isError) {

      var opt = $.extend({
         onError : function(message) { // Default function for errors
            this.html('Error: ' + message + '.').css('color', 'red');
        }
      }, options);

      // Loop each selection item
      this.each(function() {

         if(isError) // An error occurred, call opt.onError
         {
            opt.onError.call($(this), "Message");
            return true; // End of the current element process
         }

         $(this).html("Success"); // No errors, set success text

      });

   };
})(jQuery);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

但经过思考,我认为更简洁的方法是让用户也定义一个 onSuccess 回调,而不是使用 .css,让用户定义成功和错误情况的两个类,并将它们设置在元素上。

示例:

(function($) {
   $.fn.attach = function(options, isError) {

      var opt = $.extend({
         onError : function(message) { // Default function for errors
            $(this).html('Error: ' + message + '.');
        },
        onSuccess: function(message) {
            $(this).html('Success');
        },
        errorClass: 'error',
        successClass: 'success'
      }, options);

      // Loop each selection item
      this.each(function() {

         var method = 'onSuccess',
             cssClass = 'successClass';


         if(isError) // An error occurred, call opt.onError
         {
            method = 'onError';
            cssClass = 'errorClass';
            return true; // End of the current element process
         }

         opt[method].call(this, 'Message');
         $(this).removeClass(cssClass === 'successClass' ? opt.errorClass : opt.successClass)
                .addClass(opt[cssClass]);    
      });
   };
})(jQuery);

请注意,我还将 call($(this),...) 更改为 call(this, ...),以便回调的行为方式与传统的回调。


尽管如此,要回答所提出的问题:要让 css 触发事件,您可以像这样包装函数:

(function($) {
    var orig_css = $.fn.css;
    $.fn.css = function() {
        var result = orig_css.apply(this, arguments);
        if(arguments.length === 2) { // CSS property was set
            $(this).trigger('css_changed'); // or whatever event you want to trigger
        }
        return result;
    };
}(jQuery));

演示

But after thinking about it, in my opinion a cleaner approach would be to let the user define an onSuccess callback as well, and instead of using .css, let the user defined two classes for the success and error case and set them on the element.

Example:

(function($) {
   $.fn.attach = function(options, isError) {

      var opt = $.extend({
         onError : function(message) { // Default function for errors
            $(this).html('Error: ' + message + '.');
        },
        onSuccess: function(message) {
            $(this).html('Success');
        },
        errorClass: 'error',
        successClass: 'success'
      }, options);

      // Loop each selection item
      this.each(function() {

         var method = 'onSuccess',
             cssClass = 'successClass';


         if(isError) // An error occurred, call opt.onError
         {
            method = 'onError';
            cssClass = 'errorClass';
            return true; // End of the current element process
         }

         opt[method].call(this, 'Message');
         $(this).removeClass(cssClass === 'successClass' ? opt.errorClass : opt.successClass)
                .addClass(opt[cssClass]);    
      });
   };
})(jQuery);

Note that I also change call($(this),...) to call(this, ...) so that the callbacks behave the same way as traditional callbacks.


Nevertheless, to answer the question stated: To let css trigger an event, you can wrap the function like so:

(function($) {
    var orig_css = $.fn.css;
    $.fn.css = function() {
        var result = orig_css.apply(this, arguments);
        if(arguments.length === 2) { // CSS property was set
            $(this).trigger('css_changed'); // or whatever event you want to trigger
        }
        return result;
    };
}(jQuery));

DEMO

不必在意 2025-01-09 09:51:51

另一种更简单的方法可能是使用类并且不存储旧类。当出现错误时,分配错误类别。使用 .addClass() 标记错误状态,成功后,使用 .removeClass 删除错误类(如果存在)。如果它不存在,jQuery 就会继续前进,不会出现任何错误。

A different and simpler route might be to work with classes and not store the old class. when there's an error, assign the error class. Use .addClass() to mark the error state, and on success, use .removeClass to remove an error class if present. If it's not present, jQuery just moves on without any errors.

抹茶夏天i‖ 2025-01-09 09:51:51

您可以为 .css() 创建一个包装函数来执行此操作。

您的函数 .mycss() 将非常简单。您可以将要设置的样式作为参数,就像 .css() 一样。您可以使用 .data() 记录当前的 CSS,以便稍后检索。然后你照常使用 .css() 来设置你想要的样式。

您可以创建第二个 .resetcss() 函数来检查与所选元素关联的数据并将该数据设置为 CSS。或者,您可以将此功能放入 .mycss() 中,这样,如果您传递样式参数,它会存储/设置 CSS;如果您在不带参数的情况下发送它,它会恢复 CSS。

您的具体需求可能略有不同,但您可以修改函数来满足这些需求。在设置新数据之前,您可能需要检查存储的样式数据,并决定是恢复旧样式还是使用新样式。或者,如果您使用 CSS 类(一个不错的选择),您可以创建一个 .myclass() 函数来存储您以前的类并设置一个新类,以便您稍后检索该类。

You could make a wrapper function for .css() that does this.

Your function, .mycss(), would be pretty simple. You take the style that you want to set as a parameter, just like .css(). You record the current CSS with .data() so you can retrieve it later. Then you use .css() as normal to set the style you want.

You can make a second .resetcss() function to check for data associated with the selected element and set that data as your CSS. Or you could roll this functionality into .mycss() so it stores/sets CSS if you pass a style parameter and restores CSS if you send it without a parameter.

Your exact needs may be a little different, but you can modify the function(s) to meet those needs. You may want to check for stored style data before you set new data and decide if you revert to the old style or use the new one. Alternately, if you go with CSS classes (a good choice) you could make a .myclass() function instead that stores your previous class and sets a new class, allowing you to retrieve that later instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文