![](/img/trans.png)
[英]Why am I getting “ReferenceError: getElementById is not defined”?
[英]Why am I getting a ReferenceError: not defined
我試圖將jQuery添加到我的頁面,但我收到此錯誤:ReferenceError:未定義預覽
我的主題的js目錄中有一個js文件:
jQuery(document).ready(function() {
function preview() {
var hoverhome = 'url("images/Screen2.png") no-repeat';
var empty = '';
//home
$('nav .home a').hover(function() {
$('.viewport').css('background-image', hoverhome);
});
$('nav .home a').onmouseout(function() {
$('.viewport').css('background-image', empty);
});
}
});
我在我的函數文件中有這個:
function add_my_script() {
wp_enqueue_script(
'preview',
get_template_directory_uri() . '/js/scriptfile.js',
array('jquery')
);
}
這是我的html頭標記:
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<title><?php wp_title('|','true','right'); ?><?php bloginfo('name'); ?></title>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<script type='text/javascript' src='<?php bloginfo('template_url'); ?>/scriptfile.js? ver=1.7.1'></script>
<?php wp_head(); ?>
</head>
這是在我的標題中調用函數:
<div class="viewport">
<script type="text/javascript"><!--//--><![CDATA[//><!--
preview();
//--><!]]></script>
</div>
最后,這是我的css:
.viewport
{
height: 400px;
width: 400px;
position: relative;
top: -90px;
margin: 0 auto;
}
但。 我在firebug中收到此錯誤:
ReferenceError: preview is not defined
您已在函數內定義了preview
。 它將其范圍限定為該函數,因此它不是全局函數,您無法從該函數內部以外的任何位置調用它。
擺脫了
jQuery(document).ready(function() {
});
包裝。 它沒有做任何有用的事情,它破壞了你的代碼。
您還需要確保在與調用它或前一個腳本相同的腳本中定義preview
。 (或者您需要延遲執行,如下所述)。
請注意,如果您在觸摸的元素存在之前調用preview
,那么它將不會執行任何操作。 因此,您還需要確保在調用它時,它們存在后才會這樣做。 將呼叫直接置於標頭中可能不會這樣做。 將調用移動到頁腳或將其包裝在document.ready事件處理程序中(正如您當前為函數聲明所做的那樣)。
在定義之前調用preview()
函數。 該功能定義於
jQuery(document).ready(function()
{
...HERE
}
只有在加載完整個HTML后才能執行HERE。 刪除preview()
調用,並在定義后添加:
jQuery(document).ready(function()
{
function preview()
{
var hoverhome = 'url("images/Screen2.png") no-repeat';
var empty = '';
//home
$('nav .home a').hover(function()
{
$('.viewport').css('background-image', hoverhome);
});
$('nav .home a').onmouseout(function()
{
$('.viewport').css('background-image', empty);
});
}
preview();
});
你不應該添加
<script type='text/javascript' src='<?php bloginfo('template_url'); ?>/scriptfile.js? ver=1.7.1'></script>
到你的<head>
。
您應該像這樣掛鈎您的函數add_my_script
(您可以在add_my_script
函數之后添加以下代碼段):
add_action( 'wp_enqueue_scripts', 'add_my_script' );
將它掛鈎到wp_enqueue_scripts
,WordPress會在調用wp_head();
時自動添加腳本wp_head();
在您的頭文件中。
要避免確定范圍錯誤,請移除document ready
包裝器:
function preview() {
//the rest of your code here
}
在DOM准備好之后調用該函數:您的代碼應該是:
<div class="viewport">
<script type="text/javascript"><!--//--><![CDATA[//><!--
jQuery(document).ready(function($){
preview();
});
//--><!]]></script>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.