2017-01-23 68 views
0

我有期待「這個」,以作爲一個參數被傳遞,但我想傳遞一個不同的對象,而無需移動觸發功能的功能,所以目前我有這樣的:將「this」傳遞給函數的等價物是什麼?

onclick="showCalendarControl(this);" 

而是我會喜歡這樣做:

onclick="showCalendarControl(document.getElementById('somethingelse'));" 

這是行不通的,我試圖做一些不可能的事情嗎?

+1

什麼是「這不起作用」是什麼意思?控制檯中出現錯誤?有些東西獲取/不適用於錯誤的元素? – Xufox

+0

你可以只傳遞字符串並讓函數處理它嗎? –

+0

showCalendarControl函數做了什麼?需要查看更多代碼 –

回答

0

嘗試使用.bind()函數。 Docs

bind的第一個參數將設置函數'this參數(替換默認值),所有其他參數在調用該方法後會轉換爲參數。

例子:

onclick="showCalendarControl.bind(this)" //the this-statement inside of showCalendarControl will be the specified one 

onclick="showCalendarControl.bind(something, this);" //this will be passed as first argument to showCalendarControl 

編輯:測試出來後,似乎.bind()不在onclick處理工作。但是,你最初的想法工作,或者至少是我理解爲你的問題(通過document.getElementById結果到你的方法)

function showCalendarControl(obj) { 
 
    obj.innerHTML = "YEY"; 
 
}
<body> 
 
    <div id="something" onclick="showCalendarControl(document.getElementById('somethingelse'));">Click Me</div> 
 
    <div id="somethingelse"></div> 
 
</body>

如果你想參數傳遞給函數的this聲明綁定,你可以試試這個(使用call()函數,而不是我的初始綁定的):

function showCalendarControl() { 
 
    this.innerHTML = "YEY"; 
 
}
<body> 
 
    <div id="something" onclick="showCalendarControl.call(document.getElementById('somethingelse'));">Click Me</div> 
 
    <div id="somethingelse"></div> 
 
</body>

+0

你怎麼知道'showCalendarControl'接受多個參數? – gus27

+0

在JavaScript中,所有方法都接受可變輸入長度。它只是一個閱讀與否的問題 –

+0

當然,你怎麼知道'showCalendarControl'讀取第二個參數?在這個問題上我找不到任何暗示。 – gus27

相關問題