簡體   English   中英

在網頁上運行JS函數時出現問題

[英]issue running a JS function on a webpage

我試圖使用javascript函數使一個簡單的輸入文本框消失,而我使用css使其消失,但是使其淡入和淡出的javascript部分無法正常工作。 我從這里得到了小提琴。

頁面的淡化版本如下所示:

<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感到恐懼,我嘗試按照另一個堆棧溢出頁面上的提琴指令操作,但我不知道為什么它不會執行。 我嘗試了所有可能想到的東西。 有人可以幫忙嗎?

不要忘記導入JQuery庫。

另外(這與您的問題無關),將{}放在控制塊( 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM