简体   繁体   中英

load an image after clicking a button

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

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

<button rel=

to

<button data-rel=

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM