我有一个带有自定义模板的“Chess”页面。当我在线使用cheessboard.js脚本时没有问题。当我想使用它的下载版本并将<base href="http://chessboardjs.com/" />
替换为本地路径时,它会在浏览器上产生此错误:
GET http://localhost/css/chessboard.css (index):4
GET http://localhost/js/chess.js (index):8
GET http://localhost/js/jquery-1.10.1.min.js (index):9
GET http://localhost/js/chessboard.js (index):10
Uncaught ReferenceError: $ is not defined
如何调整模板Chess.php
?
...
<html>
<head>
<base href="http://chessboardjs.com/" />
<link rel="stylesheet" href="/css/chessboard.css" />
</head>
<body>
<div id="board" style="width: 400px"></div>
<script src="/js/chess.js"></script>
<script src="/js/jquery-1.10.1.min.js"></script>
<script src="/js/chessboard.js"></script>
<script>
var init = function() {
var board, game = new Chess();
var makeRandomMove = function() {
var possibleMoves = game.moves();
if (game.game_over() === true || game.in_draw() === true || possibleMoves.length === 0) return;
var randomIndex = Math.floor(Math.random() * possibleMoves.length);
game.move(possibleMoves[randomIndex]);
board.position(game.fen());
window.setTimeout(makeRandomMove, 500);
};
board = new ChessBoard('board', 'start');
window.setTimeout(makeRandomMove, 500);
};
$(document).ready(init);
</script>
</body>
</html>
...
答案 0 :(得分:2)
<base>
属性specifies the base URL to use for all relative URLs contained within a document。而且您可能会将文件放在主题目录中,我们可以使用get_stylesheet_directory_uri()
。
正确的是使用wp_enqueue_scripts
加载JS和CSS文件,并且只在需要它们的页面上执行。此外,不要从外部来源排队外部jQuery,使用与WP捆绑的那个:wp_enqueue_script('jquery');
。
你也可以create a shortcode。以下只是目录/wp-content/themes/your-theme/chessboardjs/
中Chessboardjs文件的原始示例。模板page-chess.php
就是这样:
<?php
/**
* Template Name: Chess
*/
$base = get_stylesheet_directory_uri() . '/chessboardjs';
?><html>
<head>
<link rel="stylesheet" href="<?php echo $base; ?>/css/chessboard-0.3.0.min.css" />
<script src="<?php echo $base; ?>/js/chess.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="<?php echo $base; ?>/js/chessboard-0.3.0.min.js"></script>
</head>
<body>
<div id="board" style="width: 400px"></div>
<script>
var init = function() {
var board, game = new Chess();
var makeRandomMove = function() {
var possibleMoves = game.moves();
if (game.game_over() === true || game.in_draw() === true || possibleMoves.length === 0) return;
var randomIndex = Math.floor(Math.random() * possibleMoves.length);
game.move(possibleMoves[randomIndex]);
board.position(game.fen());
window.setTimeout(makeRandomMove, 500);
};
var cfg = {
pieceTheme: '<?php echo $base; ?>/img/chesspieces/wikipedia/{piece}.png',
position: 'start'
};
board = new ChessBoard('board', cfg);
window.setTimeout(makeRandomMove, 500);
};
jQuery(document).ready(init);
</script>
</body>
</html>