【问题标题】:Jquery each and Selector behaving differentlyJquery each 和 Selector 行为不同
【发布时间】:2014-11-15 10:15:19
【问题描述】:

我在 Jquery 中创建了一个函数,它应该使元素垂直居中(我无法使用 css 做到这一点,累了,只是以编程方式完成了 ^^)。现在的问题是我最初使用 .each 创建它,然后,由于它已经是创建者,我尝试使用选择器 ($('something').center) 调用它,但由于某种原因它的行为有所不同。

使用选择器,它似乎对每个元素都做了同样的事情。它对第一个元素执行此操作,然后将所有值应用于其余元素。因此,例如,我的函数获取元素高度并对其进行一些操作,但选择器仅获取第一个,然后将其参数应用于每个人..

我会继续使用每一个,因为它现在效果最好,但我仍然不明白他们为什么这样做..

居中功能:

$.fn.center = function (){
/*If this is the highest element, or
  if this element has full use of the width,
  then there's no need to align it.
 */

if(this.height() == this.parent().height() ||
this.width() == this.parent().width())
{
    this.css({
        position : "relative",
        top : 0
    });
}
else //Should be aligned.
{
    this.css({
        position : "relative",
        top : (this.parent().height()/2)-(this.height()/2)
    });
}
return this; //Used for chaining.

};

这是我的意思的一个例子^^ http://jsfiddle.net/lrojas94/pmbttrt2/1/

【问题讨论】:

    标签: javascript jquery html css web


    【解决方案1】:

    对于简单的事情,比如只是为所有具有相同类的元素以相同的方式更改 CSS,您可以直接调用它而无需使用 .each()。例如:

    $('.elem').css('color', '#fff');
    

    但如果每个 div 都需要以单独的值结尾,则应使用 .each()。例如(抱歉有点奇怪):

    var border = 1;
    $('.elem').each(function() {
        $(this).css('border', border + 'px solid #000');
        border += 1;
    });
    

    基本上,如果您不使用.each(),它会检查您想要更改的内容(只需一次!)并将其应用于该类的所有元素。如果您确实使用了.each(),它将为每个元素单独执行。

    【讨论】:

    • 不太清楚这如何回答问题?
    • 问题是为什么“Jquery each and Selector”行为不同;这就是我试图回答的......
    • 是的 :) 非常感谢!
    【解决方案2】:

    简单地说,jQuery 插件函数中的this 不是 DOM 节点。它是一个 jQuery 对象,它包裹了选择器匹配的所有节点。

    你的函数体应该看起来像:

    return this.each(function () {
        var $el = $(this);
    
        //centering logic for $el goes here
    });
    

    【讨论】:

    • @Godisgood 不想以某种方式加载,但基本上用我在答案中编写的代码替换插件函数中的所有代码。然后,将你之前的所有代码放在var $el = ...; 之后,最后将旧代码中的this 替换为$el
    • 我使用“this”是因为我尝试遵循 Jquery 插件教程。这是一个链接:learn.jquery.com/plugins/basic-plugin-creation 它声明你应该使用 this 而不是 $this
    猜你喜欢
    • 2011-09-30
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2011-07-19
    • 2017-08-07
    • 2020-07-07
    相关资源
    最近更新 更多