问题描述
我想在此之前加上我对JavaScript非常新的事实。感谢您对我的耐心。
I want to preface this with the fact that I am very very new to JavaScript. I appreciate your patience with me.
我正在尝试创建一个脚本,允许用户在文本区域输入名称,按提交,图像为根据该名称显示。
I'm trying to create a script that allows a user to input a name into a text-area, press submit and an image is displayed based on that name.
我设法得到了这个:
<html>
<body>
<form>
<input type="text" value="" id="imagename">
<input type="button" onclick="window.location.href='http://webpage.com/images/'+document.getElementById('imagename').value +'.png'" value="GO">
</form>
</body>
</html>
这几乎完全符合我的需要 - 加载用户输入的图像。但我想要的不是图像在新窗口中打开,或者下载到我的电脑 - 我希望它在点击时显示在页面上,如图像。
Which almost does exactly what I need -loads an image around what a user inputs. But what I want is not for the image to open in a new window, or download to my computer - I want it to display on the page when clicked as an image like the example here.
我确信我对Javascript的经验不足是我无法解决的主要原因想出这个。上面的脚本是我可以得到的,而不会搞砸了。任何帮助都表示赞赏。
I'm sure that my inexperience with Javascript is the main cause of my being unable to figure this out. The script above is as far as I can get without screwing things up. Any help is appreciated.
推荐答案
单击该按钮时,获取输入的值并使用它来创建图像元素附加到正文(或其他任何地方):
When the button is clicked, get the value of the input and use it to create an image element which is appended to the body (or anywhere else) :
<html>
<body>
<form>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
</form>
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
var val = document.getElementById('imagename').value,
src = 'http://webpage.com/images/' + val +'.png',
img = document.createElement('img');
img.src = src;
document.body.appendChild(img);
}
</script>
</body>
</html>
jQuery中相同:
the same in jQuery:
$('#btn').on('click', function() {
var img = $('<img />', {src : 'http://webpage.com/images/' + $('#imagename').val() +'.png'});
img.appendTo('body');
});
这篇关于Javascript:从网址加载图片并显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!