2011-12-14 39 views
2

我試圖做一個參考生成器。人們填寫一些信息,然後生成器以正確的方式設置文本。下面是我到目前爲止有:刪除變量,如果沒有填寫

$('#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。」。

所以我的問題是:如果沒有填寫變量,我該如何省略那個變量位?

+0

那麼代碼並不是最優的,就像你說的那樣,但是你確實有了'if(variable ==「」)`部分。因此,在創建`completeString1`時使用相同的技巧。 – Jon 2011-12-14 13:01:24

+0

,你可以將你的'非空'驗證在1如果陳述,與或運營商 – bondythegreat 2011-12-14 13:04:54

回答

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; 
0

您可以使用條件運算符:

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

如果edition爲true,它將返回questionmark後的第一個值,否則返回冒號後的值。 這將工作,因爲「」(一個空字符串)評估爲false。

0

你已經有了,如果塊只有當值填充操作,只是在那裏創建的字符串:

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

剛剛建立的5個步驟的字符串,而沒有文字將被添加如果評價爲false