簡體   English   中英

顯示/隱藏提示文本

[英]Showing/hiding hint text

我創建了一個.js文件,其中包含以下內容:

$('.emailhinttext').hide();
$('select').change(function() {
if ($(this).val() == 'For yourself, your church, school, a friend etc...') {
    $('.emailhinttext').show();
}
if ($(this).val() == 'A Charity like Oxfam, Marie Curie or Help the Aged') {
    $('.emailhinttext').hide();
}
});

它確實還有其他一些東西(這有關系嗎?),我將文件與 jQuery 一起包含在我頁面的 header 中。

我的 html 是:

<div class="input select">
    <label for="I am raising money for">I am raising money for...</label>
    <select name="data[I am raising money for]" id="I am raising money for">
        <option value="0">A Charity like Oxfam, Marie Curie or Help the Aged</option>
        <option value="1">For yourself, your church, school, a friend etc...</option>
</select></div>
<div class="input text required">
    <label for="UserEmail">Email&nbsp;&nbsp;<div class="emailhinttext">*Please use the same email as your paypal account</div></label>
    <input name="data[User][email]" type="text" maxlength="255" id="UserEmail" />
</div>

即使在 jsfiddle 上一些非常相似的東西可以正常工作,它也不起作用。 我究竟做錯了什么?

val() 是 0 或 1(value 屬性的值),而不是選項標簽內的文本。 因此更改為if ($(this).val() == 1)將解決您的問題

檢查幾件事,您在腳本之前引用 jQuery,還要確保您的腳本包含在 document.ready 調用中,例如:

$(document).ready(function(){
    // your code goes here
});

有什么幫助嗎?

這種情況經常發生; 加載頁面時不會執行您的 jQuery 代碼。 您需要將其包裝在$(document).ready() function 中,如下所示:

$(document).ready(function()
{
    $('.emailhinttext').hide();

    $('select').change(function() 
    {
        if ($(this).val() == 'For yourself, your church, school, a friend etc...') 
        {
            $('.emailhinttext').show();
        }
        if ($(this).val() == 'A Charity like Oxfam, Marie Curie or Help the Aged') 
        {
            $('.emailhinttext').hide();
        }
    });
});

這將在文檔加載后執行 jQuery,而不是讓它只是坐在 DOM 中而不做太多。

暫無
暫無

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

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