Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Add image to textarea onclick

I am trying to add each different image I click on into the textarea, but I can only get the first image to add.

Just to add I am using Owl Carousel. So here is what the html looks like:

<div class="item link" id="images_available">
    <img src="https://s3.amazonaws.com/msluploads/'.$image['name'].'" class="img-responsive img-post"/>
    <div class="after">                                                                     
        <span class="zoom">
            <i class="fa fa-check text-success"></i>
        </span>
    </div></div>

The HTML above gets duplicated for every image that is displayed.

Here is what I got so far:

$('.link').on('click', function(event){
        var $this = $(this);
        var someimage = document.getElementById('images_available');
        var myimg = someimage.getElementsByTagName('img')[0];
        var mysrc = myimg.src;
        if($this.hasClass('clicked')){
            $this.removeAttr('style').removeClass('clicked');                 
        } else {
            $this.addClass('clicked');
            tinyMCE.get('post_imagetxt').setContent(mysrc);
        }
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If

The HTML above gets duplicated for every image that is displayed.

is completely true, you will have the id images_available in your DOM multiple times. Ids have to be unique though. You always get the first one because

document.getElementById('images_available');

will always get you the first element with this id since it doesn't expect any others in the DOM.

You should be able to fix this by just using this instead of someimage:

var myimg = this.getElementsByTagName('img')[0];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...