我想在更改输入值时更新变量searchUrl
。但是,input.value
不会向searchUrl
添加任何内容。另一方面,如果您在控制台上看到它,input.value
每次更新时都会有不同的值,但不会添加到searchUrl
。我做错了什么?
let input = Array.prototype.slice.call(document.getElementsByClassName("searchbox__input"))[0];
let wikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&uselang=user&search=";
let searchUrl = wikiUrl + input.value;
$(".searchbox__input").on("changed keyup", function() {
console.log(searchUrl);
console.log(input.value);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="wikipedia.css">
</head>
<body>
<div class="searchbox">
<input class="searchbox__input" type="text">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="wikipedia.js"></script>
</body>
&#13;
答案 0 :(得分:1)
将searchUrl
移至事件中,searchUrl
的值未更新,因为您未在changed keyup
事件期间添加输入值
let input = Array.prototype.slice.call(document.getElementsByClassName("searchbox__input"))[0];
let wikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&uselang=user&search=";
let searchUrl
$(".searchbox__input").on("changed keyup", function() {
searchUrl = wikiUrl + input.value;
console.log(searchUrl);
console.log(input.value);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="wikipedia.css">
</head>
<body>
<div class="searchbox">
<input class="searchbox__input" type="text">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="wikipedia.js"></script>
</body>
&#13;