显示/隐藏提示文本

时间:2011-07-10 10:50:47

标签: javascript jquery

我创建了一个.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一起包含在我的页面的标题中。

我的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上,一些非常相似的东西也可以正常工作。我做错了什么?

3 个答案:

答案 0 :(得分:2)

val()是0或1(value属性的值),而不是option标记内的文本。因此,更改为if ($(this).val() == 1)将解决您的问题

答案 1 :(得分:1)

检查一些内容,在脚本之前引用jQuery,同时确保脚本包含在document.ready中,如下所示:

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

有任何帮助吗?

答案 2 :(得分:0)

这种情况发生了很多;加载页面时不会执行您的jQuery代码。您需要将其包装在$(document).ready()函数中,如下所示:

$(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中没有做太多。