2009-05-12 5 views
0

저는 Prototype을 사용 중이며 루프의 변수에 동적으로 액세스하려고합니다.자바 스크립트가있는 onclick 속성의 변수 범위

코드 나보다 더 나은 말 :

for (var i=0;i<5;i++) { 
    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$('parent' + i).remove()" />', {position: 'after'}); 
} 

문제는 내가 취소 버튼 중 하나를 클릭하면 "내가 정의되지 않은"것입니다.

"i"가 각 버튼에 적절한 값을 유지하도록 변수 범위를 어떻게 변경합니까? 나는 어떤 직업에 관심이 없다.

답변

2

나는 parent 대신에 인용 된 문자열에 i을 넣었을 것이라고 생각합니다 (개념적으로 말하면 범위가 잘못되었습니다).

for (var i=0;i<5;i++) 
{ 
    $('parent' + i).insert(
     '<input type="button" value="Cancel" onclick="$(\'parent' + i + 
     '\').remove()" />', {position: 'after'}); 
} 
+0

우리가 '$을하는 동안 ('상위 1을 추가 할 필요가 없습니다 ') 프로토 타입을? 그는 \ '을 (를) 사용하여 이스케이프 처리해야합니다. – Kirtan

+0

예, 당신이 옳다고 생각합니다. –

2

당신은 이런 식으로 작업을 수행 할 수 있습니다 -

for (var i = 0; i < 5; i++) { 

    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$(\'parent' + i + '\').remove()" />', {position: 'after'}); 
} 

는 그것은 다음과 같이 렌더링됩니다 - 등등

<input type="button" value="Cancel" onclick="$('parent1').remove()" /> 
<input type="button" value="Cancel" onclick="$('parent2').remove()" /> 
<input type="button" value="Cancel" onclick="$('parent3').remove()" /> 
... 

하고 있습니다.

1

당신은 그 변수가 필요하지 않습니다.

<input type="button" value="Cancel" onclick="this.parentNode.parentNode.removeChild(this.parentNode)" /> 

또는 당신이 정말 원한다면, 당신은 할 수 있습니다 : 당신이 입력의 부모를 제거하려면, 할

for (var i=0;i<5;i++) { 
    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$(\'parent' + i + '\').remove()" />', {position: 'after'}); 
} 
관련 문제