12

google apps 스크립트 사용 매개 변수를 전달하는 js 함수를 실행하는 데 문제가 있습니다. 매개 변수를 추가하면 단추를 클릭 할 때 대신 페이지가로드 될 때 항상 코드가 실행됩니다. 그것은 ...onclick 함수가 자동으로 실행됩니다.

document.getElementById('button1').onclick = doSomething; 

버튼을 누를 때 실행하지만 전화 (및 기능) 아래에 매개 변수를 추가 할 때, 그냥 실행 - HtmlService 예에서 직접

, 그것은 OK입니다 일단 페이지가로드 (아닌 버튼을 누를 때) ...

document.getElementById('button1').onclick = doSomething('with_this_parameter'); 

을이 행동에 대한 모든 통찰력을 크게 감상 할 수 때 ... 미안 대답은 명백한 경우! 당신이

document.getElementById('button1').onclick = doSomething('with_this_parameter'); 

을 말할 때

+3

함수 참조 뒤에있는'()'는 항상 함수를 호출합니다. –

답변

24

이 통화 해봐요 다음 ('with_this_parameter')하고 document.getElementById('button1').onclick에 반환 값을 할당하는 것을 의미한다. 따라서 코드가 해당 행에 도달 할 때 이것이 호출되는 이유입니다. 값을 해당 속성에 할당 할 수 있는지 여부는 또 다른 질문이지만 호출되는 이유입니다.

document.getElementById('button1').onclick = function(){ 
    doSomething('with_this_parameter'); 
} 

참조처럼 사용이 솔루션은 Mark Linus에 의해 주어졌다.

+0

정보 주셔서 감사합니다 : –

+1

+1 때문에 설명이 –

+1

당신을 환영합니다. 마크 리누스 (Mark Linus)가 제안한 답변은 그것을 수행하는 방법입니다 –

9

과 같이 수행

document.getElementById('button1').onclick = function(){ 
    doSomething('with_this_parameter'); 
} 
+0

감사합니다. 그것이 간단하다는 것을 아십시오 : D –

1

을 나는 보통과 같이 clickHandlers을 수행

// create button here or get button... 
var button1 = document.getElementById('button1').setName('button1'); 
var clickHandler = app.createServerClickHandler('doSomething'); 
button.addClickHandler(clickHandler); 

function doSomething(e){ 
    var button1 = e.parameter.button1; 
    <do something with var button> 
} 

을 당신이 추가하는 것을 매개 변수 모르겠지만, 당신이 전달하는 콜백 요소를 추가해야 .setId/getId 또는 .setTag/getTag를 통해 버튼 자체에서 전달되지 않는 경우. 텍스트 상자의 경우 :

var textbox = app.createTextBox(); 
var button1 = 
app.createButton.setName('button1'); 
var clickHandler =   
app.createServerClickHandler('doSomething').addCallbackElement(textBox); 
button1.addClickHandler(clickHandler); 

희망이 있습니다.

관련 문제