HTML不调用外部JS文件

时间:2014-09-08 17:21:39

标签: javascript html

HTML:

<!DOCTYPE html>
<html>
    <head>
        <script src="adlocationverify.js"></script>
        <!--other script and also external css included over here-->
    </head>

<body>
    <form>
        Sales Rep: <input type="text" name="salesrep" required><br>
        Customer Name: <input type="text" name="customer" required><br>
        Target URL: <input type="text" name="url1" required><br>
        Target URL: <input type="text" name="url2"><br>
        Target URL: <input type="text" name="url3"><br>
        Number of Impressions: <input type="number" name="impressions" min="100000" required><br>
        Start Date: <input type="date" name="startdate" required><br>
        End Date: <input type="date" name="enddate" required><br>
        Geo Target (Optional): <input type="text" name="geo"><br>
        Technologies (Optional): <input type="text" name="tags"><br>
        Ad Locations: <input type="checkbox" name="top"> Top Leaderboard <input type="checkbox" name="middle"> Middle Leaderboard <input type="checkbox" name="sidebar"> Sidebar<br>
        <input type="submit" name="submit" onClick="validateadlocation()">
    </form>
</body>
</html>

JS:

<script>
function validateadlocation()
{
    var checkboxs=document.getElementsByName("top middle sidebar");
    var okay=false;
    for(var i=0,l=checkboxs.length;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
        }
    }
    if(okay)alert("Thank you for checking a checkbox");
    else alert("Please check a checkbox");
}
</script>

javascript与HTML内联时有效,但在尝试从外部文件调用时无效。

2 个答案:

答案 0 :(得分:2)

js文件不应包含<script></script>标记。标签应该只包含在html文件中。

答案 1 :(得分:1)

如果您从外部文件调用JS,则需要删除&lt; SCRIPT&gt;&lt; / SCRIPT&gt; 标记,否则您将收到错误。

您的js文件必须只包含Javascript代码:

function validateadlocation()
{
    var checkboxs=document.getElementsByName("location");
    var okay=false;
    for(var i=0,l=checkboxs.length;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
        }
    }
    if(okay)alert("Thank you for checking a checkbox");
    else alert("Please check a checkbox");
}