简体   繁体   中英

How to pass a reference to 'this' into a function? [duplicate]

This question already has an answer here:

How do you reference a button by 'this' and pass it into a function?

$(document).on("click", ".join-group-btn", function () {
                    var groupid=$(this).val();
                    var button=$(this);
                    joinGroup(groupid, button);
                });

Then I keep the joinGroup function in my library on a separate page:

function joinGroup (groupid, buttonIn) {
    var button = $(buttonIn);
    var l = Ladda.create(document.querySelector(buttonIn));
}

Id's won't work as the buttons are generated dynamically.

This throws:

Dom exception 12: An invalid or illegal string was specified

Thanks for the help! It is greatly appreciated.

You should use querySelector with CSS-alike syntax selectors

your buttonIn is a jQuery object element

document.querySelector(buttonIn) // you need to pass a String selector
                                 // like "#someId",
                                 // not an jQuery object

An example would be:

$(document).on("click", ".join-group-btn", function () {
    joinGroup( this.value,  $(this),  this.id  );
});


function joinGroup ( value,  $this,  id) {
    // console.log( value );     // "Some Value"
    // console.log( $this );     // [Object] the clicked jQuery Element 
    // console.log(  id   );     // "someID"
    // Now if you want to use querySelector
    var theButton = document.querySelector("#"+ id); // The missing #
    // Or Directly operate over the `button` Element object argument
    // $this.css({color:"red"}); // Cause it's a jQuery element
}

document.querySelector expect a selector string. But your function needs a DOM-object right? You can pass it so:

function joinGroup (groupid, buttonIn) {
    var l = Ladda.create(buttonIn[0]);
}

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