简体   繁体   中英

Passing “this” and “event” in JS function

I have a button with an onclick event as follows:

<button type="button" onclick="captions(event)">
     <img src="someimg.png">
</button>

I need to be able to change the img src without using an ID to reference it. I want to pass "this" and the event (I need to do some other things that require event to be passed) but I cannot get this to work. Example of JS is below:

function captions(event) {
             this.src = this.src.replace("img2.png");
}

Thanks!

I suggest not using inline event handlers. You should bind the event "unobtrusively" using JavaScript.

First give the button a class:

<button type="button" class="captions">
     <img src="someimg.png">
</button>

Then bind the event:

window.onload = function(){
    var captions = document.getElementsByClassName('captions');
    for(var i = 0, len = captions.length; i < len; i++){
        captions[i].addEventListener('click', function(event){
            // this is your button, what you clicked on
            // you need to get the image
            var image = this.getElementsByTagName('img')[0];

            // this.src.replace("img2.png") doesn't do what you think it does
            // String.replace takes 2 parameters
            image.src = '/your/new/image';
        });
    }
};

DEMO: http://jsfiddle.net/WcFzq/

You can get the element that was clicked using the event.target property ( http://www.w3schools.com/jsref/event_target.asp ).

function captions(event) {
         event.target.src = "img2.png";
}

Here is a jsfiddle .

Following will solve your problem.

function captions(event) {
   var img = this.childNodes[0];
   img.src = img.src.replace("img2.png");
}

If you want to do an inline onclick event, you should simply be able to pass a new variable that captures the element into the function, like this:

function captions(element, event) {
    . . . do stuff . . .
}

Then you would call it, passing this in for the element parameter, like this:

<button type="button" onclick="captions(this, event);">
    <img src="someimg.png">
</button>

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