输入时的 Jquery .val() 返回 [对象未定义]
我想将 with href 附加到 Google 的 favicon 获取器,其中包含单击按钮时输入的值。
我想要实现的结果是:
<img href="https://s2.googleusercontent.com/s2/favicons?domain=https://google.com/">
实际结果:
<img href="https://s2.googleusercontent.com/s2/favicons?domain=[object Undefined]">
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="upload.js"></script>
<style>
#e-favicon {
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<input type="text" id="input">
<button id="button">Get favicon</button>
<div id="e-favicon"></div>
</body>
</html>
const element = "#e-favicon";
const button = "#button";
const input = "#input";
$(document).ready(function() {
console.log("js loaded");
$(button).on('click', function () {
const favicon = "https://s2.googleusercontent.com/s2/favicons?domain=" + toString($(input).val());
console.log("button click");
console.log(favicon);
$(element).append('<img href="' + favicon + '">');
});
});
I want to append an with href to Google's favicon fetcher with the value from an input when the button is clicked.
The result I want to achieve is:
<img href="https://s2.googleusercontent.com/s2/favicons?domain=https://google.com/">
The actual result:
<img href="https://s2.googleusercontent.com/s2/favicons?domain=[object Undefined]">
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="upload.js"></script>
<style>
#e-favicon {
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<input type="text" id="input">
<button id="button">Get favicon</button>
<div id="e-favicon"></div>
</body>
</html>
const element = "#e-favicon";
const button = "#button";
const input = "#input";
$(document).ready(function() {
console.log("js loaded");
$(button).on('click', function () {
const favicon = "https://s2.googleusercontent.com/s2/favicons?domain=" + toString($(input).val());
console.log("button click");
console.log(favicon);
$(element).append('<img href="' + favicon + '">');
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
转换为字符串是导致意外结果的原因。您不需要将
.val()
转换为字符串,因为它返回一个字符串值:Converting to string is what is causing an unexpected result. You don't need to convert
.val()
to string since it returns a string value: