Javascript 如果body id是特定值,则执行函数

Javascript 如果body id是特定值,则执行函数,javascript,function,exists,Javascript,Function,Exists,我只想在我的站点的一个页面上执行一个函数,其中主体ID为#modulePage16460412。我下面的脚本不起作用 <script type="text/javascript"> if($('#modulePage16460412').length > 0 ) { $(function() { $(window).bind('load', function(e) { window.setTimeout(function() {

我只想在我的站点的一个页面上执行一个函数,其中主体ID为#modulePage16460412。我下面的脚本不起作用

<script type="text/javascript">
if($('#modulePage16460412').length > 0 ) {
$(function()
{
$(window).bind('load',
    function(e)
    {
    window.setTimeout(function()
        {
         $.colorbox({opacity:0.3, href:"/storage/support/colorbox/offer.html"});
        }, /*timeout->*/ 2000);
    });
});
}
</script>

如果($('#modulePage16460412')。长度>0){
$(函数()
{
$(窗口).bind('load',
职能(e)
{
setTimeout(函数()
{
$.colorbox({opacity:0.3,href:“/storage/support/colorbox/offer.html”});
},/*超时->*/2000);
});
});
}
是否也可以只在他们第一次访问页面时执行该函数,而在他们返回该页面时不再执行该函数


任何帮助都将不胜感激。

您需要将条件放入
$(function(){
中,以便在JavaScript查询(卸载的)DOM是否存在ID之前实际加载body标记

$(function(){
    if($('#modulePage16460412').length) {

        ...

    }
});

您可以定义一个函数,但不能在任何地方调用

所以把所有的东西都放在函数和调用中

还可以将此if($('#modulePage16460412').length>0)替换为if($('#modulePage16460412')),因为当jquery找不到id为:#modulePage16460412的元素时,它将返回空数组。empty_array.length=0,因此它将始终为真

$('document').ready(function(){

if($('#modulePage16460412')) {
$(function()
{
$(window).bind('load',
    function(e)
    {
    window.setTimeout(function()
        {
         $.colorbox({opacity:0.3, href:"/storage/support/colorbox/offer.html"});
        }, /*timeout->*/ 2000);
    });
});
}

});

您只需使用指定的ID将函数加载到body load上即可…如果不存在具有此ID的元素,则函数将永远不会启动

$('#modulePage16460412').load(function() { // this will not be called unless an element with that ID has loaded into the DOM

     // ... your code here.

});
谈到“单次执行”部分(这确实应该是一个新问题……但哦,好吧),您可以使用localStorage来持久化设置

就你的情况来说

if( !getData('someKey') ) {
   // ok so they have not been here.
   setData('someKey', 1); //  now set the data so this won't get hit again.
} 

也许是一种更简单的方法

$( document ).ready( function() { // runs code only after DOM ready
   if ( $( '#modulePage16460412' ).length > 0 ) { // runs code only if id found
       window.setTimeout( function() {
          $.colorbox( { opacity:0.3, href:"/storage/support/colorbox/offer.html" } );
       }, 2000 );
   }
} );

为什么不在脚本中使用此函数,只将其添加到应该使用它的页面上的HTML中?问题的第二部分需要使用Cookie或localStorage。在这种情况下,我更喜欢localStorage,因为服务器确实不关心此信息,所以为什么要将其存储在Cookie中并发送到服务器..localStorage只存在于客户端上。完美的解决方案scott.korin!肯定是一个“为什么我没有想到那个”的时刻:)谢谢!@rlemon-你知道关于如何使用localStorage的好资源吗?谢谢!我会在MDN页面上查找它。