如何传递对'这'转换为函数

How to pass a reference to 'this' into a function?

本文关键字:函数 转换 何传递      更新时间:2023-09-26

如何通过"this"引用按钮并将其传递到函数中?

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

然后我将joinGroup函数保存在我的库中的一个单独的页面上:

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

Id不起作用,因为按钮是动态生成的。

这抛出:

Dom exception 12: An invalid or illegal string was specified

谢谢你的帮助!非常感谢。

document.querySelector需要一个选择器字符串。但是你的函数需要一个DOM对象,对吧?你可以通过这样:

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

您应该将querySelector与类似CSS的语法选择器一起使用

您的buttonIn是一个jQuery对象元素

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

例如:

$(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
}