gpt4 book ai didi

javascript - 使 jQuery 函数单独运行

转载 作者:行者123 更新时间:2023-11-27 22:36:39 24 4
gpt4 key购买 nike

我创建函数来获取具有相同类“视差”的某些不同 div 的特定高度,问题是它可以工作,但它只能获取第一个 div 的高度并将其应用于其他 div。这里是我的代码,请建议我该怎么办,我还是个初学者。

 jQuery.fn.do_para = function() {
var section_effect = jQuery(this);
var height = section_effect.height();
alert(height);
//do something with height
}

if(jQuery('.page_section').hasClass('parallax')) {
jQuery(this).do_para();
}

html 看起来像这样

 <div class="page_section parallax" style="height:500px"></div>
<div class="page_section"></div>
<div class="page_section parallax" style="height:700px"></div>

最佳答案

问题是因为 jQuery 插件外部的 this 引用了 jQuery 对象/集合本身,而不是该集合的各个元素。所以,而不是:

 jQuery.fn.do_para = function() {
var section_effect = jQuery(this);
var height = section_effect.height();
alert(height);
//do something with height
}

您应该使用:

 jQuery.fn.do_para = function() {

// if you don't want to return the collection
// omit the 'return' (but this will break
// the traditional jQuery chaining if you do):
return this.each(function(){

// within the each() method 'this' refers
// to each individual element of the
// collection passed to the plugin:
var section_effect = jQuery(this);

var height = section_effect.height();
alert(height);
//do something with height
});
}

问题涉及整个集合的原因是,当 jQuery 方法用作 getter 时(使用该方法而不传递参数),它将引用集合中的第一个元素,并返回该元素的值第一个元素。

如果您出于某种原因想要检索值数组,您可以使用: jQuery.fn.do_para = 函数() { varsection_effect = jQuery(this);

    // here we use the map() method to iterate over
// the collection and, from each element in the
// collection, return the height:
var height = section_effect.map(function(){
$(this).height();

// here we use get() to turn the jQuery map into
// an Array:
}).get();

alert(height);
//do something with height
}

顺便说一句,如果在插件的代码中,您想使用 jQuery 的别名——如果没有别的办法的话,可以节省打字时间——那么您可以按照以下方式编写您的插件,使用 Immedately -调用的函数表达式:

// the argument to the function is the
// alias with which you refer to
// jQuery:
(function ($) {

$.fn.do_para = function(){
return this.each(function(){
var section_effect = $(this);
// rest of your code..
});
});

// passing jQuery into the function:
})(jQuery);

引用书目:

关于javascript - 使 jQuery 函数单独运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39063224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com