0

我有个问题。通过下面的代码,.srch-inpt的值会根据所选的选项类别而变化。现在我需要在焦点上删除.srch-inpt的值并将其重新设置为模糊。我写的代码不能正常工作..如果有人可以帮助我,我很感激..谢谢!

小提琴演示

这是我的 HTML:

<select class="srchopts">
    <option class="bookopt">Book Option</option>
    <option class="articleopt">Article Option</option>
    <option class="thesisopt">Thesis Option</option>
    <option class="journalopt">Journal Option</option>
</select>
<input type="text" name="" class="srch-inpt" value="Title / Author / Keywords / ISBN" defaultValue="" />

和我的 jQuery 代码:

//Changing search value on select-box option change
$(function(){
    $('.srchopts').change(function () {
        var optclass = "";
        $("select option:selected").each(function () {
            optclass += $(this).attr('class');
        });
        if (optclass == 'bookopt' || 'thesisopt' ) {
            $('.srch-inpt').val('Title/ Author/ Keyword/ ISBN');
        }
        if (optclass == 'articleopt' ) {
            $('.srch-inpt').val('Title/ Author/ Keyword/ Doi');
        }
        if (optclass == 'journalopt' ) {
            $('.srch-inpt').val('Title/ ISSN');
        }
    });
    $('.srch-inpt').focus(function() {
        if ($(this).val() == $(this).attr('defaultValue'))
            $(this).val('');
        }).blur(function() {
            if ($(this).val() == '')
            $(this).val( $(this).attr('defaultValue') );
        });     
});
4

2 回答 2

0
$('.srch-inpt').data('defaultValue','My default value').focus(function () {
    if (this.value === $(this).data('defaultValue')) this.value = "";
}).blur(function () {
    if (!this.value.length) this.value = $(this).data('defaultValue');
}).blur();

演示

于 2013-09-15T16:51:39.843 回答
0

我得到了 A. Wolff 提到的点的答案。由于我们在新 jQuery 中没有“DefaultValue”属性,我必须自己创建它,并在每次更改.srch-inpt值时更新它的值。

所以,这是我的新 jQuery 代码:

//Changing search value on select-box option change
$(function(){
    $('.srchopts').change(function () {
        var optclass = "";
        $("select option:selected").each(function () {
            optclass += $(this).attr('class');
        });
        if (optclass == 'bookopt' || 'thesisopt' ) {
            $('.srch-inpt').val('Title/ Author/ Keyword/ ISBN');
        }
        if (optclass == 'articleopt' ) {
            $('.srch-inpt').val('Title/ Author/ Keyword/ Doi');
        }
        if (optclass == 'journalopt' ) {
            $('.srch-inpt').val('Title/ ISSN');
        }

        $('.srch-inpt').attr('defaultValue', $('.srch-inpt').val());
    });
    $('.srch-inpt').focus(function() {
        if ($(this).attr('defaultValue') == '')
            $(this).attr('defaultValue', $(this).get(0).defaultValue);


        if ($(this).val() == $(this).attr('defaultValue'))
            $(this).val('');
    }).blur(function() {
        if ($(this).val() == '')
            $(this).val( $(this).attr('defaultValue') );
    });     
});

演示

于 2013-09-16T05:33:42.730 回答