2017-02-23 21 views
0

我有圖像鏈接的列表,並且想要編寫一個按鈕,在該鏈接上激活onClick事件。所以:jQuery - 觸發事件,而不是設置它

「沒有按鈕點擊」:點擊鏈接重定向我們 「按鈕被點擊後」:點擊鏈接帶給我們的編輯對話框

Java腳本:(「#設置-ICO」的按鈕)

eventsHandler  : function() { 

    var self = this; 

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - * 

    $("#settings-ico").on("click", function() { 

     $(".b-row > a").on("click", tileOpenDialog(event)); 
    }); 

    $("#tile-edit-save").on("click", tileEditSave()); 

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - * 

    function tileOpenDialog(event) { 

     event.preventDefault(); 
     let id = $(this).prop("id"); 
     this.editId = id; 
     $("#tile-edit").css("display", "block"); 
     console.log(id + ' click'); 
     alert(self.pageList); 
    } 
    function tileEditSave() {} 
} 

的按鈕「#設置-ICO」,並點擊它馬上給我帶來我的編輯對話框,不點擊任何鏈接。

$("#tile-edit").css("display", "block");

但我想,是顯示這個對話框中,單擊後某些環節:

$(".b-row > a").on("click", tileOpenDialog(event)); 

如何編寫代碼呢?爲什麼點擊按鈕後觸發'titleOpenDialog()'?

回答

1

當您將它們作爲回調傳遞時,您不應該調用函數。除非他們正在返回另一個功能,我猜。你正在做的:

$(".b-row > a").on("click", tileOpenDialog(event)); 

當你應該做的:

// Passing in the named function so that it can be called 
// later once the button is clicked 
$(".b-row > a").on("click", tileOpenDialog); 

或者,如果你想在事件對象傳遞明確的,你可以這樣做:

// Creating and passing in an anonymous function that will be 
// called later once the button is clicked, which will in turn 
// call the inner function. 
$(".b-row > a").on("click", function(event) { 
    tileOpenDialog(event) 
}); 

作爲一個解釋當你點擊#settings-ico時發生了什麼,基本上一旦你點擊它正在運行jQuery函數來選擇.b-row > a。然後它對返回值運行.on()方法,並傳遞字符串"click",然後運行到tileOpenDialog(event)。由於後面有括號,因此JavaScript引擎必須先運行該函數(這就是對話框打開的原因),然後將返回值(undefined)作爲第二個參數傳遞給.on()

+0

謝謝,它現在正在工作。關於事件對象,我只是讀了沒有必要傳遞它,jQuery自動傳遞它。 – linearSpin

+0

沒問題。很高興我能夠提供幫助。 – Sam

相關問題