最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I load an image after clicking a button? - Stack Overflow

programmeradmin0浏览0评论

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

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

Here is its jsfiddle.

Now I found that the rel is not valid for the <button>.

I'm interested to know other solutions to do this, such as using jquery .data()

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

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

Here is its jsfiddle.

Now I found that the rel is not valid for the <button>.

I'm interested to know other solutions to do this, such as using jquery .data()

Share Improve this question edited Apr 18, 2024 at 13:43 isherwood 61.1k16 gold badges121 silver badges169 bronze badges asked Aug 28, 2013 at 9:08 Farzad BayanFarzad Bayan 2512 gold badges4 silver badges13 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 3

HTML

<button data-rel="example.jpg">Click Me</button>

jQuery

$("button").click(function () {
    var imgUrl = $(this).data('rel');
    $("#area").html("<img src='" + imgUrl + "' alt='description' />");
});

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/x3QdU/4/

change

<button rel=

to

<button data-rel=

http://jsfiddle/x3QdU/1/

发布评论

评论列表(0)

  1. 暂无评论