简体   繁体   English

显示/隐藏提示文本

[英]Showing/hiding hint text

I've created a .js file with the following in it:我创建了一个.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();
}
});

It does have a couple of other things in it (Should that matter?) and I include the file in the header of my page along with jQuery.它确实还有其他一些东西(这有关系吗?),我将文件与 jQuery 一起包含在我页面的 header 中。

my html is:我的 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>

It doesn't work even though on jsfiddle something really similar works fine.即使在 jsfiddle 上一些非常相似的东西可以正常工作,它也不起作用。 What am I doing wrong?我究竟做错了什么?

The val() is either 0 or 1 (the value of value attribute), and not the text inside the option tag. val() 是 0 或 1(value 属性的值),而不是选项标签内的文本。 So changing to if ($(this).val() == 1) will resolve your problem因此更改为if ($(this).val() == 1)将解决您的问题

Check a few things, you reference jQuery before your script, also make sure your script is wrapped in the document.ready call like:检查几件事,您在脚本之前引用 jQuery,还要确保您的脚本包含在 document.ready 调用中,例如:

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

Any of that help?有什么帮助吗?

This happens quite a lot;这种情况经常发生; your jQuery code isn't executed when the page is loaded.加载页面时不会执行您的 jQuery 代码。 You need to wrap it in a $(document).ready() function, like so:您需要将其包装在$(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();
        }
    });
});

This will execute the jQuery when the document has loaded, instead of having it just sit in the DOM not doing much.这将在文档加载后执行 jQuery,而不是让它只是坐在 DOM 中而不做太多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM