繁体   English   中英

无论如何我可以将这个javascript代码放在head标签中?

[英]is there anyway i could put this javascript code in head tag?

我的形式中有很少的div,需要首先隐藏,即onLoad。 问题是,当我把它放入<head>标签时,它将首先尝试执行div给出值为null的错误,并且当我将其包含在表单下方时,它可以完美地运行。 例如

鉴于JS代码放在下面,此代码工作正常。

<div class="error" id="name_error"><p>Input Name</p></div>
<input type="text" id="name" name="name" class="input-text" value="Enter Name..."/>

<script type="text/javascript">
     document.getElementById('name_error').style.display = 'none';
</script>

当我尝试将JS代码放在上面时它不起作用。

无论如何我可以将JavaScript代码放在head标签中,它应该在页面加载时隐藏div?

无论如何我可以将JavaScript代码放在head标签中,它应该在页面加载时隐藏div?

您需要将代码包装在onload事件中:

window.onload = function(){
  document.getElementById('name_error').style.display = 'none';
};

这样您就不会得到未定义的错误,因为当DOM与其他页面资源一起可用时会触发onload事件。

当然。 只需将其置于加载事件中,如下所示:

window.addEventListener("load", function() {
    document.getElementById('name_error').style.display = 'none';
}, false);

您可能想要考虑使用jQuery 以下是它的编写方式。

$(function(){
    $('#name_error').hide();
});

$(function(){ }); 将在加载DOM后执行,类似于window.onload ,仅支持跨浏览器。

$('#name_error')就像是使用css选择器语法的document.getElementById('name_error')的快捷方式。

.hide(); 是将style.display设置为'none'的快捷方式。

编辑:非jQuery窗口加载。

在我发布这个答案之后,我想起了Dustin Diaz关于最小的DOMReady代码的帖子。 使用他的代码,它看起来像这样。

function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
r(function(){
    document.getElementById('name_error').style.display = 'none';
});

有关第1行的更多信息, 请访问http://www.dustindiaz.com/smallest-domready-ever/

我在这里错过了什么吗? 为什么不将初始样式设为'display:none'? 而不是将其保留为默认值,然后立即隐藏它。

在window.load事件中将显示设置为none可能会导致内容最初可见 - 在闪烁消失时闪烁。 但是,正如所指出的,您无法在呈现之前更改DOM元素的显示。

一个好的方法是使用Javascript(你可以在头部做)在html元素上添加(或删除)一个类,并设置一个css规则,如果html标签有类集,则隐藏你的元素。

请参阅: 如何检测浏览器JavaScript是否已关闭并显示示例通知

有不同的方法来推迟脚本的执行有很多答案,在评论中有一些争议,所以我写了一些DEMO来比较所有这些方法的真正差异,因为它们当然不是当量。

对于那些不想看到演示的不耐烦的人,这里有一些最重要的事情要记住为工作选择合适的工具:

window.onload = function(){...};

  • 它适用于所有浏览器
  • 它删除了所有以前的处理程序
  • 它只在加载所有图像后才会触发

window.addEventListener(“load”,function(){...});

  • 它在Internet Explorer中不起作用
  • 它只在加载所有图像后才会触发

jQuery(document).ready(function(){...});

  • 它适用于所有浏览器
  • 一旦DOM准备好就会激活它

只是为了好奇,这就是jQuery实际上正在做的事情,以确保一旦DOM准备就绪并且跨浏览器工作就会解雇你的处理程序:

// Handle when the DOM is ready
ready: function( wait ) {
    // A third-party is pushing the ready event forwards
    if ( wait === true ) {
        jQuery.readyWait--;
    }

    // Make sure that the DOM is not already loaded
    if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
        // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
        if ( !document.body ) {
            return setTimeout( jQuery.ready, 1 );
        }

        // Remember that the DOM is ready
        jQuery.isReady = true;

        // If a normal DOM Ready event fired, decrement, and wait if need be
        if ( wait !== true && --jQuery.readyWait > 0 ) {
            return;
        }

        // If there are functions bound, to execute
        readyList.resolveWith( document, [ jQuery ] );

        // Trigger any bound ready events
        if ( jQuery.fn.trigger ) {
            jQuery( document ).trigger( "ready" ).unbind( "ready" );
        }
    }
},

bindReady: function() {
    if ( readyBound ) {
        return;
    }

    readyBound = true;

    // Catch cases where $(document).ready() is called after the
    // browser event has already occurred.
    if ( document.readyState === "complete" ) {
        // Handle it asynchronously to allow scripts the opportunity to delay ready
        return setTimeout( jQuery.ready, 1 );
    }

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

        // A fallback to window.onload, that will always work
        window.addEventListener( "load", jQuery.ready, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", DOMContentLoaded);

        // A fallback to window.onload, that will always work
        window.attachEvent( "onload", jQuery.ready );

        // If IE and not a frame
        // continually check to see if the document is ready
        var toplevel = false;

        try {
            toplevel = window.frameElement == null;
        } catch(e) {}

        if ( document.documentElement.doScroll && toplevel ) {
            doScrollCheck();
        }
    }
},

我将它展示为一个例子,如果你需要它可以在所有浏览器上运行而且如果某些图像或广告加载有延迟,那么像文档就绪处理程序这样的东西可能实际上非常复杂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM