【问题标题】:First time using jQuery, something its not working [closed]第一次使用jQuery,它不起作用[关闭]
【发布时间】:2014-05-07 16:26:21
【问题描述】:

我正在尝试做一个网站,从文件中读取图像,然后从这些图像中更改背景。

为此,我想使用一个名为 bgswitcher 的 jQuery:
https://github.com/rewish/jquery-bgswitcher
http://rewish.github.io/jquery-bgswitcher/

但它不起作用,这是我第一次使用 jQuery,所以我当然会犯一些愚蠢的错误。这是我的代码:

<?php
    $dir = "img/";
    $numFiles = 0;
    $fh = fopen('config.txt','r');
    $imgTime = fgets($fh);
    $transTime = fgets($fh);

    if (is_dir($dir)){
        if ($dh = opendir($dir)){
            $file = readdir($dh);$file = readdir($dh); //Para deshacerme del . i ..
            while (($file = readdir($dh)) !== false){
                $files[] = $file;
                $numFiles++;
            }
            closedir($dh);
        }
    }
?>

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Gestor Publicitari v0.2</title>
        <style type="text/css">
            body{
                background-color:white;
            }       
        </style>
        <script type="text/javascript" src="jquery-1.11.1.js"></script>
        <script language="javascript">
            var images = <?php echo json_encode($files); ?>;
            var numImg = <?php echo json_encode($numFiles); ?>;
            var imgTime = parseInt(<?php echo json_encode($imgTime); ?>)*1000;

            $('.box').bgswitcher({
                images: ["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg","img/5.jpg"],
                effect: "fade",
                interval: 500;
            });
        </script>    
    </head>
    <body>
        <div class="box">
            <p>TEST</p>
        </div>
    </body>
</html>

为了丢弃错误,我没有使用已读取的文件,而是使用了 5 个存在的示例图像。

【问题讨论】:

标签: javascript jquery html image


【解决方案1】:

首先,根据@Arun 的建议,您需要包含bgswitcher 插件。

<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script type="text/javascript" src="jquery-bgSwitcher.js"></script>

之后,由于您将 &lt;script&gt; 放在 &lt;head&gt; 部分中,因此您需要将代码包装在 DOM ready 处理程序 $(document).ready(function(){...}) 或更短的形式 $(function(){...}); 中在执行 jQuery 代码之前确保你的 DOM 元素已经正确加载

<script>
$(function() {
    var images = <?php echo json_encode($files); ?>;
    var numImg = <?php echo json_encode($numFiles); ?>;
    var imgTime = parseInt(<?php echo json_encode($imgTime); ?>)*1000;

    $('.box').bgswitcher({
        images: ["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg","img/5.jpg"],
        effect: "fade",
        interval: 500;
    });
});
</script>

【讨论】:

  • 我也喜欢使用$(document).ready(function(){...});,因为它不言自明
  • 不错的完整答案。 +1
  • 非常感谢,现在它可以完美运行并且对 jquery 有了更多的了解!啊,还有它的 jquery.bgSwitcher.js,而不是 jquery-bgSwitcher.js!!
【解决方案2】:

将代码放在 jquery 就绪函数中

$(function(){
   // your code
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2020-04-16
    相关资源
    最近更新 更多