繁体   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