2010-07-06 7 views
0

페이지의 특정 것이 변경되면 버튼에 onclick 이벤트를 제공하려고합니다. 나는 여러 가지 방법으로 노력했지만 아무도 노력하지 못했습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?JavaScript 동적 onClick 문제

다음은 내가 시도한 것입니다.

document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); }; 


document.getElementById(subDiv).onclick = "alert('Error. There is an error on the the page. Please correct that then submit the page');"; 


function redErrorAlert() 
{ 
    alert('Error. There is an error on the the page. Please correct that then submit the page'); 
} 
document.getElementById(subDiv).onclick = redErrorAlert; 



document.getElementById(subDiv).setAttribute('onclick',redErrorAlert(), false); 



document.getElementById(subDiv).setAttribute('onclick','redErrorAlert()', false); 

참고 : subDiv는 요소의 ID를 포함하는 변수입니다.

+0

jquery와 같은 js 라이브러리를 사용하는 것이 좋습니다. 오히려 쉽고 크로스 브라우저 호환. 그게 .. .. 어떤 브라우저에서 이것을 테스트하려고합니까? – spinon

+0

@spinon Chrome에서 테스트 중이지만 IE, FF 및 Chrome에서 작동해야합니다. – Jason

답변

0

jQuery 영역과 비슷합니다. 일단 jQuery의 기능을 배우면, 이와 같은 일들은 간단하게 처리 할 수 ​​있습니다. 자바 스크립트를 많이 작성하지 않을 것입니다.

먼저, 이벤트를 바인딩하는 코드에 넣고 http://jquery.com/

에서 jQuery를 얻을 :

$('#idOfElementToBindClickEvent').click(function(){ 
    alert('Error.'); 
}); 

jQuery를 기본적으로 CSS와 같은 선택기를 사용하여 요소를 조작 할 수있는 방법을 제공합니다. 함수를 호출 할 필요가, 당신은 문자열을

두 번째 경우를 할당했습니다 :

2

DOM 트리에 대한 쿼리를 만들기 전에 DOM 트리가 만들어 질 때까지 기다려야합니다.)

window.onload = function() { 
    document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); }; 
}; 
+0

이 호출시 이미로드 된 페이지입니다. 입력 상자가 변경되어 유효성을 검사하지 않을 때에 만 호출하는 함수가 호출됩니다. DOM 트리는이 시점에서 이미로드되어 있어야합니다. – Jason

1

document.getElementById를을 (당신이있어 요소의 ID를 포함하는 문자열을 취

이 모든 DOM 트리가 내장 된 후 을 생성하는 컨텍스트 내에서 발생하는지 확인 찾으려고. id가 'subDiv'인 요소를 찾고 있다고 가정하면 document.getElementById ('subDiv')를 호출해야합니다.

(그것은 당신의 코드에서 변수 subDiv는 ID를 포함하는 문자열입니다 가능성도 있습니다,하지만 당신은 내가 그렇지 않은 있으리라 믿고있어 그것을 언급하지 않았기 때문에.)

편집 :하는 경우 당신은 virstulte의 jQuery 사용에 대한 제안과 함께 갈 것이고, 코드가 실행될 때까지 DOM이 빌드되었는지 확인하기 위해 document.ready 이벤트에 함수를 첨부 할 것입니다. 예 :

$(document).ready(function() { 
    $("#subDiv").click(function() { alert("Test!"); }); 
}); 
+0

subDiv는 id를 포함하는 변수입니다. 미안합니다. – Jason

+0

아, 야곱이 말했듯이 - DOM이 아직 초기화되지 않았습니다. 나는 또한 virstulte의 jQuery 체크 아웃에 대한 훌륭한 제안을 고려할 것이다. Jacob과 virstulte의 코드를 결합하여 내 대답을 편집했습니다. – Faisal

0

document.getElementById(subDiv).onclick = alert('Error. There is an error on the the page. Please correct that then submit the page'); 

또는

function redAlert() { 
    alert('Error. There is an error on the the page. Please correct that then submit the page'); 
} 

document.getElementById(subDiv).onclick = redAlert(); 

첫 번째 경우 시도 당신은 기능을 할당 한 이 함수를 호출하지 않았다면