javascript 单击按钮后加载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18483689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
load an image after clicking a button
提问by Farzad Bayan
I have a <button>
with the rel="example.jpg"
. I want the button to load the image in my #area
DIV, just afterclicking on it, not with the page load. So I use this code and everything is done:
我有一个<button>
用rel="example.jpg"
。我希望按钮在我的#area
DIV 中加载图像,只是在点击它之后,而不是页面加载。所以我使用这个代码,一切都完成了:
$(document).ready(function(){
$("button").click(function(){
var imgUrl = $(this).attr('rel');
$("#area").html("<img src='" + imgUrl + "' alt='description' />");
});
});
<button rel="example.jpg">Click Me</button>
<div id="area"></div>
Hereis its jsfiddle.
这是它的 jsfiddle。
Now I found that the rel
is not valid for the <button>
.
现在我发现rel
对<button>
.
I'm interested to know other solutions to do this, such as using jquery .data()
我有兴趣知道其他解决方案来做到这一点,例如使用 jquery .data()
回答by Anton
HTML
HTML
<button data-rel="example.jpg">Click Me</button>
jQuery
jQuery
$("button").click(function () {
var imgUrl = $(this).data('rel');
$("#area").html("<img src='" + imgUrl + "' alt='description' />");
});
回答by Parfait
change
改变
<button rel=
to
到
<button data-rel=
回答by Flame Trap
Change your code to this:
将您的代码更改为:
$(document).ready(function(){
$("button").click(function(){
var imgUrl = $(this).data('rel');
$("#area").html("<img src='" + imgUrl + "' alt='description' />");
});
});
<button data-rel="example.jpg">Click Me</button>
<div id="area"></div>
Fiddle: http://jsfiddle.net/x3QdU/4/