簡體   English   中英

如何將對“ this”的引用傳遞給函數? [重復]

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

這個問題已經在這里有了答案:

您如何通過“ 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

謝謝您的幫助! 非常感謝。

您應該將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
}

document.querySelector需要選擇器字符串。 但是您的函數需要DOM對象嗎? 您可以這樣傳遞它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM