Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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' />");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...