仅在特定div中运行jQuery代码 [英] Run jQuery code only in a specific div

查看:68
本文介绍了仅在特定div中运行jQuery代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a homepage with the id component-homepage in the body. This page has a few animations in the footer, navigation and another element. These elements have the same name on all the other pages.

我想执行jQuery代码(js文件将包含更多只有这个代码)的元素在#component-homepage中。

I would like to execute the jQuery code (the js file will contain more then just this code) when the elements are in the #component-homepage.

// 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 ,从而运行代码。

the .length method returns the number of elements in the jQuery object, so as long as there is more than one element with this ID, this will translate to a Boolean value of true, and thus run the code.

来源

.length - jQuery API

这篇关于仅在特定div中运行jQuery代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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