gpt4 book ai didi

javascript - 在网页上运行 JS 函数的问题

转载 作者:行者123 更新时间:2023-12-03 04:15:18 24 4
gpt4 key购买 nike

我正在尝试使用 javascript 函数来使一个简单的输入文本框消失,并且我使用 css 使其消失,但是使其淡入和淡出的 javascript 部分不起作用。我从 here 得到了 fiddle 。

我的页面的淡化版本如下所示:

<html lang="en">

<head>
<title>Volunteer Form</title>
<script type="text/javascript" src="script.js"></script>
<style type="text/css">
.fieldset-auto-width {
display: inline-block;
}
.todisplay {
display:none;
}
</style>
</head>
<body>

<input type="checkbox" name="typeofwork[]" value="other" class='checkdisplay' > Other <br><br>

<div class='todisplay'>
<b>Other Tasks</b><br>
if checked other, type below.<br>
<input type="text" name="othertasks"><br><br>
</div>

<div class='todisplay'>test</div>


我在同一目录中创建了一个 javascript 文件,并将其命名为 script.js:

$(document).ready(function () {
$('.checkdisplay').change(function () {
if (this.checked) $('.todisplay').fadeIn('slow');
else $('.todisplay').fadeOut('slow');

});
});

我还尝试将相同的脚本放在页面底部的 和 标签之间,如下所示:

</body>
<script type="text/javascript" src="script.js">
$(document).ready(function () {
$('.checkdisplay').change(function () {
if (this.checked) $('.todisplay').fadeIn('slow');
else $('.todisplay').fadeOut('slow');

});
});</script>
</html>

很抱歉,我对 javascript 很糟糕,我尝试按照另一个堆栈溢出页面的 fiddle 指令进行操作,但我不知道为什么它不会执行。我尝试了我能想到的一切。有人可以帮忙吗?

最佳答案

不要忘记导入 JQuery 库。

另外(这与您的问题无关),将 {} 放在控制 block 周围(if 语句的分支,循环等)以避免混淆并防止代码中出现错误。

此外,在元素的 nameid 属性中使用特殊字符通常是个坏主意。您将 name="typeofwork[]" 作为复选框的名称。您应该考虑将其更改为字母数字值。

// This code can be in an external script file, but you will have to reference that file
// similarly to the way JQuery is imported with the HTML <script> element. Or, you
// can place this code in a <script> element and place that element at the bottom of your
// HTML (just before the closing body tag) or inside the HTML <head> section.
$(document).ready(function () {
$('.checkdisplay').change(function () {
if (this.checked) {
$('.todisplay').fadeIn('slow');
}
else {
$('.todisplay').fadeOut('slow');
}

});
});
<html lang="en">

<head>
<title>Volunteer Form</title>
<style type="text/css">
.fieldset-auto-width {
display: inline-block;
}
.todisplay {
display:none;
}
</style>

<!-- This must preceed any code that uses JQuery. It links out to that library so you can use it -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>

<input type="checkbox" name="typeofwork[]" value="other" class='checkdisplay' > Other <br><br>

<div class='todisplay'>
<b>Other Tasks</b><br>
if checked other, type below.<br>
<input type="text" name="othertasks"><br><br>
</div>

<div class='todisplay'>test</div>

关于javascript - 在网页上运行 JS 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44168883/

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