我如何告诉jQuery只在一个特定的网页上运行一个函数? [英] How do I tell jQuery to run a function on one specific web page only?

查看:144
本文介绍了我如何告诉jQuery只在一个特定的网页上运行一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些jQuery代码在网站的每个网页(在head元素)。

I have some jQuery code that is on every web page of the site (in the head element).

我可以使用什么选择器语法来告诉jQuery某些功能应该只在一个网页上运行,而不是在网站上的所有其他网页上运行?

What selector syntax can I use to tell jQuery that a certain function should only run on one page and not all the other pages on the site?

我可以在选择器中指定网页名称或网址吗?

Can I specify a page name or URL in the selector somehow?

很感谢

推荐答案

您可以使用if语句检查top.location.pathname。

You could use an if statement checking for top.location.pathname.

if (top.location.pathname === '/my/path')
{
    /* magic ... */
}

你想让它更可移植,给予实际的if语句一些意思(所以有人读它会知道它是什么) - 如果你有权访问文档的body元素,你可以添加一个类,显示你想要运行这个脚本。

Or if you want to make it more portable and give the actual if statement some meaning (so someone reading it will know what it's about) - if you have access to the body element of the document, you can add a class showing that you want to run this script.

例如,如果 / * magic ... * / 与包括Facebook的API,你可以使你的身体看起来像< body class =has-facebook-api> 然后用jQuery检查:

So for instance, if /* magic ... */ in the above example has something to do with including the Facebook API, you could make your body look like <body class="has-facebook-api"> and then make a check with jQuery:

$(function () // on document.ready()
{
    if ($('body.has-facebook-api').length > 0)
    {
        /* magic ... */
    }
});

确保在将jQuery包含在单独的脚本标记之后运行。

Make sure this runs after including jQuery inside a separate script tag.

在我们使用它的时候,如果你不使用这个脚本来转换你的页面的视觉效果输出之前,我会建议你将您的所有或大部分脚本标记放在页脚附近,以更快地呈现页面。

While we're at it, if you're not using this script to transform the visuals of your page before it gets outputted, I'd advise you to place all or most of your script tags close to your footer to render the page sooner.

这篇关于我如何告诉jQuery只在一个特定的网页上运行一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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