2015-03-30 178 views
0

如何通過'this'引用按鈕並將其傳遞給函數?如何將對'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)); 
} 

標識的將無法工作。

此拋出:

Dom exception 12: An invalid or illegal string was specified 

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

+0

'Ladda.create'作爲參數期待什麼,它有什麼作用? – Musa 2015-03-30 21:11:08

+0

您已經將按鈕作爲一個元素髮送。你不必做'$(buttonIn)','buttonIn'已經是你想要的元素了。 – 2015-03-30 21:11:10

回答

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 
} 
0

document.querySelector期望選擇串。但是你的函數需要一個DOM對象嗎?你可以通過它:

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