gpt4 book ai didi

javascript - 如何将 javascript 添加到 HTML 页面?

转载 作者:太空宇宙 更新时间:2023-11-04 13:46:33 24 4
gpt4 key购买 nike

我是 web 开发的新手,我想将以下功能添加到我的简单 html 页面,但是如果我按“单击我”不会发生任何事情。描述部分不隐藏和显示

This is the code I tried

我添加了如下代码。 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>

最佳答案

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

HTML:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

JS:

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

fiddle 之所以有效,是因为 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>

关于javascript - 如何将 javascript 添加到 HTML 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28292965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com