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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:05:39  来源:igfitidea点击:

load an image after clicking a button

javascriptjqueryhtml

提问by Farzad Bayan

I have a <button>with the rel="example.jpg". I want the button to load the image in my #areaDIV, just afterclicking on it, not with the page load. So I use this code and everything is done:

我有一个<button>rel="example.jpg"。我希望按钮在我的#areaDIV 中加载图像,只是点击它之后,而不是页面加载。所以我使用这个代码,一切都完成了:

$(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 relis 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=

http://jsfiddle.net/x3QdU/1/

http://jsfiddle.net/x3QdU/1/

回答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/

小提琴:http: //jsfiddle.net/x3QdU/4/