如何重写jQuery的show()和hide()函数 [英] How to override jquery's show() and hide() functions

查看:186
本文介绍了如何重写jQuery的show()和hide()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短版本的问题:请参见标题

Short version of question: see title

长版问题: 我在代码中广泛使用了jquery的show()和hide()函数,只是遇到了一个问题:它们通过将元素的显示属性分别更改为'block'或'none'来工作,因此如果您有一个显示的内容:内联然后隐藏并显示,您已将其显示更改为阻止",这在某些情况下会弄乱布局.

Long version of question: I've used jquery's show() and hide() functions extensively in my code and just encountered a bit of a problem: they work by changing the display attribute of the element to 'block' or 'none' respectively, so that if you have somethin that has display: inline and then hide and show it, you've changed its display to block, which screws up the layout in a couple of cases.

在我的代码中,每当我希望最初隐藏某些东西时,我都会给它一个隐藏"类.此类仅为{display:none}.我希望更改显示和隐藏以删除或添加此类,而不是直接更改显示属性,因此,如果您添加隐藏的类然后再次将其删除(即隐藏并显示某些内容),那么它又回到了原来的状态.最初是因为(因为添加类会覆盖属性,而不是直接更改属性).像这样的东西(这有点伪,因为我不知道如何正确设置功能-假设'this'是调用show/hide的对象)

In my code, whenever i want something to be hidden initially i give it a class 'hidden'. This class is simply {display: none}. I'd like the change show and hide to remove or add this class, instead of directly changing the display attribute, so that if you add the hidden class and then remove it again (ie hide and show something) then it's back to exactly how it was to start off with (since adding a class overrides the attributes rather than directly changing them). Something like this (this is a little pseucodey as i don't know how to set the function up properly - let's assume that 'this' is the object that show/hide was called on)

function show(){
  this.removeClass("hidden");
} 

function hide(){
  this.addClass("hidden");
} 

我将如何以及在何处覆盖jquery方法? (我不是JavaScript专家)

how and where would i go about overriding the jquery methods? (I'm not a javascript expert)

感谢-最高

推荐答案

当您可以创建自己的方法时,我不会覆盖jQuery的方法.覆盖很可能会导致插件发生意外行为.

I wouldn't override jQuery's methods when you could create your own. Overriding would very likely cause unexpected behavior in plugins.

jQuery已经有一个名为toggleClass()的方法,该方法似乎可以满足您的需求.

jQuery already has a method called toggleClass() that would seem to fit what you're looking for.

$someElement.toggleClass('hidden');

文档: http://api.jquery.com/toggleClass/

但是要回答您的特定问题,要覆盖jQuery方法,您可以执行以下操作:

But to answer your specific question, to override a jQuery method, you would do something like this:

jQuery.fn.show = function() {
    // Your custom code
}

或创建自定义方法:

jQuery.fn.customMethod = function() {
    // Your custom code
}

在执行此操作之前,最好先查阅此文档:

Before doing so, it would be a good idea to consult this document:

http://docs.jquery.com/Plugins/Authoring

这篇关于如何重写jQuery的show()和hide()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆