setinterval says not defined function but it is

2019-02-28 18:14发布

问题:

i have this function which i define inside HEAD:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js">
function live() {
    $.get("http://mydomain.com/script.php", function(data){
        var timer = data;
        var elm = document.getElementById("live");
        if (timer == 1){
         elm.style.display = 'block';
        } else{
         elm.style.display = 'none';
        }     
    });
}
</script>

and then i do a loop like this at the very end of my document:

<script type="text/javascript">
 setInterval(live,10000);
</script>

but i get an error saying live is not defined. Why is that? Could you please tell me what im doing wrong?

Thank you.

回答1:

Put your code in an separate <script> tag. As soon as a <script> tag has a src attribute, any content of that tag is ignored in favor of the given resource. so just do this:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function live() {
    $.get("http://mydomain.com/script.php", function(data){
        var timer = data;
        var elm = document.getElementById("live");
        if (timer == 1){
         elm.style.display = 'block';
        } else{
         elm.style.display = 'none';
        }     
    });
}
</script>