如果没有填写,删除变量

时间:2011-12-14 12:56:37

标签: jquery

我正在尝试制作一个参考生成器。人们填写一些信息,然后生成器以正确的方式设置文本。这是我到目前为止所得到的:

    $('#ref-button1').click(function () {
    var authorname = $('#bookAuthor').val();
        if (authorname == "") {
             $('.error').show();
             return false;
         }
    var booktitle = $('#bookTitle').val();
        if (booktitle == "") {
             $('.error').show();
            return false;
         }
    var year = $('#bookYear').val();
        if (year == "") {
             $('.error').show();
            return false;
         }
    var place = $('#bookPlace').val();
        if (place == "") {
            $('.error').show();
            return false;
         }
    var publisher = $('#bookPublisher').val();
        if (publisher == "") {
             $('.error').show();
            return false;
         }
    var edition = $('#bookEdition').val();
    var page = $('#bookPage').val();
    var completeString1 = authorname + '&nbsp;' + '(' + year + '),' + '&nbsp;' + '<i>' + booktitle + '</i>' + ',&nbsp;' + edition + '&nbsp;ed.,&nbsp;' + place + ':&nbsp;' + publisher + ',&nbsp;' + page;

    $('.error').hide();
    $('#output').empty();
    $('#output').append(completeString1);
});

如你所见,我有5个必须填写的变量,2个没有。我在completeString1中创建了整个字符串,其中我也放入了逗号等等。我知道这可能不是最简单的方法,但它是我能做到的。我现在的问题是,即使我没有填写变量,我的completeString1仍将包含并打印“ed。”。

所以我的问题是:如果没有填写变量,我怎么能忽略变量呢?

3 个答案:

答案 0 :(得分:1)

我得到的是“版本”变量有问题。因此,您需要更改为其指定值的方式:

var edition = $('#bookEdition').val() != "" ? ($('#bookEdition').val() + '&nbsp;ed.,&nbsp;') : "";

然后,将completeString1设置更新为:

var completeString1 = authorname + '&nbsp;' + '(' + year + '),' + '&nbsp;' + '<i>' + booktitle + '</i>' + ',&nbsp;' + edition + place + ':&nbsp;' + publisher + ',&nbsp;' + page;

答案 1 :(得分:0)

您可以使用条件运算符:

(edition?'&nbsp;ed.,&nbsp;':'')

如果版本为true,它将返回questionmark后面的第一个值,否则返回冒号后面的值。 这将起作用,因为“”(空字符串)的计算结果为false。

答案 2 :(得分:0)

你已经拥有了只在填写值时才会运行的if-blocks,只需在那里创建你的字符串:

var resultstring = "";
$('#ref-button1').click(function () {
var authorname = $('#bookAuthor').val();
    if (authorname == "") {
         $('.error').show();
         resultstring = authorname + '&nbsp;' + '(' + year + '),' + '&nbsp;'
    }

只需在5个步骤中构建字符串,如果if-evaluation为false,则不会添加任何文本。