我试图建立一个query parameter
进行搜索时,我设法建立它与input
字段但是有select
下拉菜单来选择其他值。动态输入并选择如何构建查询字符串
<input type="text" class="dd">
<select name="" class="sel">
<option value=""></option>
<option value="Prepare">Prepare</option>
<option value="Ready">Ready</option>
<option value="Cancel">Cancel</option>
</select>
<button onclick="buildQuery()">Build query</button>
查询构建查询参数
function buildQuery(){
var result = "?";
var getVal = $('input.dd').val();
console.log('Input > ', getVal);
var getSelectVal = $('select.sel').val();
if (getVal != null && (getVal != "")) {
let inputValues = getVal
.split("\n")
.filter(function (str) { return str !== "" })
.join("&test=");
// then add it to the overall query string for all searches
result = result + 'test' + "=" + inputValues + "&";
console.log('Results > ', result);
}
不知道我怎样才能从select
获得的价值,构建其方式类似于我的输入输出CONSOLE.LOG jQuery代码Results > ?test=f&
因此,如果您填写input
和select
一个选项,则queryParam应该说类似?test=inputVal&test=selectVal
或个人?test=inputVal
或?test=selectVal
我可以做的是复制整个if()
声明并用getSelectVal
代替getVal
,但它似乎效率低下并且复制代码。
实际代码 -
newSearchParams.properties.forEach(function (inputSearch) {
// first reparse the input values to individual key value pairs
// Checks which field is not null and with empty string (space)
var getVal = $('input.input_' + inputSearch.name).val();
var getSelectVal = $('select.select_' + inputSearch.name).val();
if (getVal != null && (getVal != "")) {
let inputValues = getVal
.split("\n")
.filter(function (str) { return str !== "" })
.join("&" + inputSearch.name + "=");
// then add it to the overall query string for all searches
result = result + inputSearch.name + "=" + inputValues + "&";
}
}, this);
// remove trailing '&'
result = result.slice(0, result.length - 1);
return result;
编辑: - 这就是我试图摆脱这个问题,
if(paramMethod == 'path'){
// build parameter api/id/1
} else if(paramMethod =='query'{
// build queryString api/apiPoint?id=1
} else if(paramMethod == 'none') {
// var result = "";
// return result;
}
两者都返回'undefined',你可以做出的jsfiddle与回答? – MrNew
那么,该函数只是返回查询字符串值。你需要另一个按钮触发的函数,它会调用buildQuery并使用它。查看小提琴的例子,我只是将输出记录到控制台。当然,你会想用它做点别的。 – shadymoses
谢谢,而不是使用'$('。dd,.sel')'我可以使用变量吗?像我在我的问题中提到的问题,如 '$('input.input _'+ inputSearch.name,'select.select _'+ inputSearch.name)'this instead – MrNew