我目前正在尝试根据用户使用JavaScript在查询表单上输入的输入构建API的URL。文本字段的输入保存在变量中,该变量进一步联合在一起作为最终URL。 然而,并非所有输入字段都将一直使用。
我想知道如果它的值为空,你如何忽略该特定变量。
正如我解释的那样,我有一组输入字段:
<input id="whoValue" type="text" value="" placeholder="Who">
<input id="whenStart" type="text" value="" placeholder="Start Date">
<input id="whenEnd" type="text" value="" placeholder="End Date">
<input id="whatValue" type="text" value="" placeholder="What">
<button id="searchBtn">Search</button></br>
<input id="result" type="text" value="" placeholder="Resulting URL">
然后按下该按钮时,即使内容为空,JavaScript也会加入输入字段。
$('#searchBtn').click(function () {
var url = 'http://particularURLof/';
var who = "…WHO" + $('#whoValue').val();
var what = "…WHAT"+ $('#whatValue').val();
var when = "…YEAR[" + $('#whenStart').val() + "+TO+" + $('#whenEnd').val() + "]";
var moreUrl = '…url End';
var resultUrl = url + who + what + when + moreUrl;
$("#result").val(resultUrl);
});
因此,如上所述,我正在尝试仅使用变量构建resultUrl
保持值 输入字段< /强>
以下是我所拥有的JSFiddle 。
答案 0 :(得分:0)
简短,如果不喜欢:
var result = if_this_is_true ? true : false;
为您提供代码示例
$('#searchBtn').click(function () {
var url = 'http://particularURLof/';
var who = $('#whoValue').val().length > 0 ? "…WHO" + $('#whoValue').val() : '';
var what = $('#whatValue').val().length > 0 ? "…WHAT"+ $('#whatValue').val() : '';
var moreUrl = '…url End';
var resultUrl = who + what + moreUrl;
$("#result").val(resultUrl);
});
答案 1 :(得分:0)
$('#searchBtn')。click(function(){
var url = 'http://particularURLof/';
var who = $('#whoValue').val();
var what = $('#whatValue').val();
var whenStart = $('#whenStart').val();
var whatEnd = $('#whenEnd').val();
var moreUrl = "endOfUrl";
if( (who != '') && (what != '') && (whenStart != '') && (whenEnd != '') ) {
var resultUrl = url + who + what + whenStart + whenEnd + moreUrl;
}
else if( (who == '') && (what != '') && (whenStart != '') && (whenEnd != '') ) {
var resultUrl = url + what + whenStart + whenEnd + moreUrl;
}
else if( (who != '') && (what == '') && (whenStart != '') && (whenEnd != '') ) {
var resultUrl = url + who + whenStart + whenEnd + moreUrl;
}
else if( (who != '') && (what != '') && ((whenStart == '') || (whenEnd == '')) ) {
var resultUrl = url + who + what + moreUrl;
}
$("#result").val(resultUrl);
});