仅在特定div中运行jQuery代码

我有一个主页上有id组件主页的主页。 此页面在页脚,导航和其他元素中有一些动画。 这些元素在所有其他页面上具有相同的名称。

当元素在#component-homepage中时,我想执行jQuery代码(js文件将包含更多,然后只包含此代码)。

// This could should be on all the pages $("nav li:last-child").addClass('last-child'); // This code should only be used when the id #component-homepage is in the body // Homepage navigatie fadeIn + contentblok animatie $('#content_home').hide(); $('nav').hide().fadeIn(1200, function(){ var result = $("#content_home").outerHeight(); $('#content_home_container').css({"margin-top": -Math.abs(result), "height": (result)}); $('#content_home').css({"margin-top": (result),"display":"block"}).animate({marginTop: '0px'},1000); }); // Homepage navigatie animatie + url click event $('nav a').click(function(event){ event.preventDefault(); var href = this.href; $('nav').animate({ marginTop: '-635px'}, 1000, function(){ window.location = href; }); $('footer').fadeOut(200); }); 

我试着在这里包装代码:

 $('#component-homepage').ready(function(){ // code }); 

但它似乎没有用。

将代码包装在此:

 if ( $('#component-homepage').length ) { // code } 

.length方法返回jQuery对象中的元素数,因此只要有多个具有此ID的元素,这将转换为布尔值true ,从而运行代码。

来源(S)

.length – jQuery API

您可以将上下文传递给jQuery选择器,它们只能在该范围内工作:

 $('nav a', someDOMNode) 

如果我认为那是你所追求的是正确的……