【发布时间】:2022-02-10 19:56:40
【问题描述】:
我有这样的表格:
<form>
<input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/>
<button type="submit" id="findWord" class="btn btn-primary">Search</button>
<div>
<input type="radio" value="exact match" id="exact-match">
<label for="exact-match" class="checked" checked>Exact match</label>
<input type="radio" value="all matches" id="all-matches">
<label for="all-matches">All matches</label>
</div>
</form>
因为我不能在这个项目中使用name="" 作为单选按钮,所以我编写了一个脚本来使用一个类来切换它们。
let radioBtns = document.querySelectorAll('input[type="radio"]');
function toggleCheck() {
radioBtns.forEach(function (radioBtn) {
radioBtn.classList.toggle('checked');
radioBtn.classList.contains('checked') ? radioBtn.checked = true : radioBtn.checked = false;
});
}
radioBtns.forEach(function (radioBtn){
radioBtn.addEventListener('click', toggleCheck, false);
});
let anyMatch = document.getElementById('all-matches').classList.contains('checked');
console.log(anyMatch);
let exactMatch = document.getElementById('exact-match').classList.contains('checked');
console.log(exactMatch);
根据选择的电台,我必须进行不同的查询。
如果我选择exact match,输入中的单词将包含引号(queryWithQuotes)。
如果我选择all matches,则输入中的单词不包含引号(queryWithoutQuotes)。
let pageUrl = window.location.protocol + "//" + window.location.host;
const searchTerm = document.getElementById("searchedWord").value.replace("'", "''");
if (exactMatch === true) {
let queryWithQuotes = pageUrl + "/_api/search/query?querytext='" + '"' + searchTerm + '"' + "'&selectproperties='Path%2cUrl'&sourceid='xxxxx'";
console.log(`queryWithQuotes variable is: ${queryWithQuotes }`);
$.ajax(
{
url: queryWithQuotes,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: success,
error: error
}
);
} else if (anyMatch === true) {
let queryWithoutQuotes = pageUrl + "/_api/search/query?querytext='" + searchTerm + "'&selectproperties='Path%2cUrl'&sourceid='xxxxx'";
console.log(`queryWithoutQuotes variable is: ${queryWithoutQuotes }`);
$.ajax(
{
url: queryWithoutQuotes,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: success,
error: error
}
);
} else {
console.log('There is an error');
}
由于某些原因,搜索只考虑了exact match。即使我切换到All matches,搜索也会继续Exact match。
是什么原因?
【问题讨论】:
标签: javascript jquery ajax forms radio-button