【发布时间】:2022-01-06 20:33:51
【问题描述】:
function pageKeywords(searchValue){
const pageKeywords = {
"home": "/homepage",
"about": "/about-us",
"about us": "/about-us"
}
const getInputVal = searchValue;
if (pageKeywords[getInputVal]) {
console.log(pageKeywords[getInputVal])
window.location.href = pageKeywords[getInputVal];
} else {
console.log('not found')
}
}
$(document).ready(function(){
$("#searchKeywords").on("keypress", function(e) {
if (e.which === 13) {
pageKeywords($(this).val())
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="searchKeywords">
我想通过输入查找页面 url。我有一个包含关键字和网址的对象。然后回车时会做检查,如果关键字相同或存在,则显示url,否则显示未找到。
例如在输入中我输入“home”,当我输入时会显示 url “/homepage”,因为关键字存在,如果我输入“contact”,它会显示未找到,因为关键字不存在存在。
我已经制作了如下代码,但为什么找不到呢?
$(document).ready(function(){
$("#searchKeywords").on("keypress", function(e){
if(e.which == 13){
const map = {
"home" : "/homepage",
"about" : "/about-us"
}
const searchVal = $("#searchKeywords").val()
Object.entries(map).map((k,v) => {
if(searchVal == k[0]){
console.log(k[1])
}else{
console.log("not found")
}
});
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="searchKeywords">
【问题讨论】:
-
熟悉how to access and process nested objects, arrays or JSON 并使用
Object的可用静态和实例方法。请注意,您尝试使用Array的那些;您似乎将普通对象与数组混淆了。你试过pageKeywords[$(this).val()]和pageKeywords.hasOwnProperty($(this).val())吗? -
map()将在浏览器开发工具控制台中抛出错误。你没有提到任何错误。该错误消息也可用于进行网络搜索,可能会给你一个很大的线索 -
我在@SebastianSimon 上方编辑了我的描述和代码
标签: javascript jquery object javascript-objects