我創建了代碼來檢查輸入搜索框中的一個特定值。如果是這樣,網路將聚焦于被搜索的元素。
我的HTML
<input type="search" id="search-box" placeholder="Search">
< button type="submit" id="searchbar" onclick="Focus()" < /button>Search< /button>
我的JavaScript
function Focus(){
var search = document.getElementById("search-box"/span>).value。
if(search == "about"){
document.getElementById("about").focus()。
}
else{
alert("未找到")。
}
}
這樣做是可行的,但如果我改成這樣
if(search == "about" || "About")
那么else陳述句就不起作用了。
是否有其他方法可以使about區分大小寫? 像About, AbOut, aBoUT等都是一樣的
。uj5u.com熱心網友回復:
你總是可以做到:
const toCompare = 'AboUT'/span>;
if(toCompare.toLowerCase() === 'about'/span>){
/--。
}else{
/--
uj5u.com熱心網友回復:
你可以使用下面的if陳述句
。if (search == "about" || search == "About"){}。
但是正如你所提到的,可能會有許多大寫字母和簡單的組合。因此,你應該將所有的文本轉換為簡單的(轉換為標準格式),并像下面這樣進行檢查。
if (search.toLowerCase() == "about"){}。
uj5u.com熱心網友回復:
if(search == "about" || "About")將總是評估為真,因為 "About "是一個非空字串,是Truthy。
你需要寫 if(search == "about" || search == "About")/code>
另外,一個更好的語法是不區分大小寫,寫成
if(search.toLowerCase() == "about" )
uj5u.com熱心網友回復:
你可以使用search.toLowerCase() == "about"來查看它是否是一個不區分大小寫的匹配。請確保你使用了正確的引號。因為你在某些情況下使用了大寫的引號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/314486.html
標籤:
