如何将JavaScript添加到HTML页面?

DSM*_*DSM 2 html javascript jquery html5

我是网络开发的新手,我想在我的简单html页面中添加以下功能,但是如果我按下"click me"就不会发生任何事情.描述部分不隐藏和显示

这是我试过的代码

我添加了以下代码.CSS工作得很好.但JavaScript不起作用.我该如何解决这个问题

<html>
<head>
<title>TEST</title>
<link rel="stylesheet" type="text/css" href="hpcss.css">
<script>
// Hide all the elements in the DOM that have a class of "box"
$('.box').hide();

// Make sure all the elements with a class of "clickme" are visible and bound
// with a click event to toggle the "box" state
$('.clickme').each(function() {
    $(this).show(0).on('click', function(e) {
        // This is only needed if your using an anchor to target the "box" elements
        e.preventDefault();

        // Find the next "box" element in the DOM
        $(this).next('.box').slideToggle('fast');
    });
});
</script>


</head>
<body align="center">
<a href="#" class="clickme">Click Me</a>
<div class="box">
    First Description
</div>

<a href="#" class="clickme">Click Me</a>
<div class="box">
    Second Description
</div>


</body>

</html>
Run Code Online (Sandbox Code Playgroud)

epo*_*och 5

您需要导入jQuery,并且只在jQuery加载后运行代码

HTML:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

JS:

$(function() {
    // your code here
})
Run Code Online (Sandbox Code Playgroud)

小提琴正在运行,因为jsfiddle自动运行DOM加载,并jQuery为您插入.

这是jsfiddle(幕后)的实际来源:

<script type='text/javascript'>//<![CDATA[ 
$(function(){
// Hide all the elements in the DOM that have a class of "box"
$('.box').hide();

// Make sure all the elements with a class of "clickme" are visible and bound
// with a click event to toggle the "box" state
$('.clickme').each(function() {
    $(this).show(0).on('click', function(e) {
        // This is only needed if your using an anchor to target the "box" elements
        e.preventDefault();

        // Find the next "box" element in the DOM
        $(this).next('.box').slideToggle('fast');
    });
});

});//]]>  

</script>
Run Code Online (Sandbox Code Playgroud)