javascript函数无法正常调用

时间:2013-12-11 03:46:06

标签: javascript php function loops

<html>
<head>
    <title>Get HTML code from any web page</title>
    <script src="js/jquery.min.js"></script>
    <script src="js/jquery.xdomainajax.js"></script>
    <script src="js/clientJs.js"></script>
    <link rel="stylesheet" href="style.css" type="text/css" media="screen"/>
</head>
<body>
<div class="result"></div>
</body>
</html>

<?php
require_once('../connect.php');
error_reporting(-1);
function number_pad($number, $n)
{
    return str_pad((int)$number, $n, "0", STR_PAD_LEFT);
}

function GetLastChapter($id)
{
    $query = mysql_query("select*from tchapter where id_komik='$id' order by chapter desc limit 0,1") or die(mysql_error());
    $row = mysql_fetch_assoc($query);
    return $row['chapter']+1;
}
$manga_Array = array
(
    array("1","http://www.komikid.com","Naruto",GetLastChapter(1),"18"),
    array("4","http://www.komikid.com","One_Piece",GetLastChapter(4),"18")
);

foreach ($manga_Array as $manga) {
    print_r($manga); echo "<br>";
    $page = 0;
    $now = 1;
    while ($page < $manga[4]) {
        $page = number_pad($now, 2);
        $now++;

        $url = "$manga[1]/$manga[2]/$manga[3]/$page/";
        ?>
        <script>
            var myurl = '<?php echo $url ?>';
            setTimeout(function() {
                getHTMLContent(myurl,<?php echo $manga[0]; ?>,<?php echo $manga[3]; ?>);
            }, <?php echo $now * 5000 ?>);
        </script>
    <?php
    }
}
?>

上面有我用于从我的网站抓取图像的代码,但我认为它无法正常工作,每次调用url的函数getHTMLcontent始终是相同的url。抱歉我的英语不好,我希望你们明白我的意思。

2 个答案:

答案 0 :(得分:2)

setTimeout调用的函数将引用相同的变量“myurl”。您可以将参数传递给函数:

<script>
var myurl;

myurl = 'URL 1';
setTimeout(function(url) {
    alert(url);    // 'URL 1'
}, 3000, myurl);

myurl = 'URL 2';
setTimeout(function(url) {
    alert(url);    // 'URL 2'
}, 6000, myurl);
</script>

答案 1 :(得分:1)

您正在使用myurl的全局变量。

<script>
    setTimeout(function() {
        getHTMLContent('<?php echo $url ?>', <?php echo $manga[0]; ?>, <?php echo $manga[3]; ?>);
    }, <?php echo $now * 5000 ?>);
</script>