Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅在特定div中运行jQuery代码_Jquery - Fatal编程技术网

仅在特定div中运行jQuery代码

仅在特定div中运行jQuery代码,jquery,Jquery,我有一个在正文中带有id组件主页的主页。此页面在页脚、导航和其他元素中有一些动画。这些元素在所有其他页面上具有相同的名称 当元素位于#组件主页中时,我希望执行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

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

当元素位于#组件主页中时,我希望执行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
,从而运行代码

来源


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

$('nav a', someDOMNode)

如果我正确地假设这就是你想要的…

我不能100%确定你的意思。我知道我可以为选择器指定某个div。但是在编码中重复你自己是不好的。@Peter:如果在我误解了你的问题之后,比利的答案与你的答案是一样的,那么我的答案就不相关了;对不起,太好了。这正是我想要的。您的代码行执行以下操作:它检查#组件主页中是否有html,如果有,它运行代码,否则不运行。这是正确的吗?我一定会在几分钟内给出正确的答案。不完全正确-它会检查是否有ID为#component homepage的元素,如果有,它会运行代码,否则它不会-我想这就是你想要的。看看Hi Peter,如果我的答案帮助你,请将其标记为正确。:)该死的!反正忘了;)再次感谢。