我有期待「這個」,以作爲一個參數被傳遞,但我想傳遞一個不同的對象,而無需移動觸發功能的功能,所以目前我有這樣的:將「this」傳遞給函數的等價物是什麼?
onclick="showCalendarControl(this);"
而是我會喜歡這樣做:
onclick="showCalendarControl(document.getElementById('somethingelse'));"
這是行不通的,我試圖做一些不可能的事情嗎?
我有期待「這個」,以作爲一個參數被傳遞,但我想傳遞一個不同的對象,而無需移動觸發功能的功能,所以目前我有這樣的:將「this」傳遞給函數的等價物是什麼?
onclick="showCalendarControl(this);"
而是我會喜歡這樣做:
onclick="showCalendarControl(document.getElementById('somethingelse'));"
這是行不通的,我試圖做一些不可能的事情嗎?
嘗試使用.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>
什麼是「這不起作用」是什麼意思?控制檯中出現錯誤?有些東西獲取/不適用於錯誤的元素? – Xufox
你可以只傳遞字符串並讓函數處理它嗎? –
showCalendarControl函數做了什麼?需要查看更多代碼 –