2012-01-03 8 views
0

저는 꽤 오래 동안 웹 개발을 해왔지만, 최근에야 <input type="image"> 태그의 존재를 발견했습니다.이미지 버튼 클릭 시뮬레이션 방법

웹 페이지에 다음 양식을 자동으로 제출하는 greasemonkey 스크립트가 있습니다.

<form id="form1"> 
     <input id="radio1" type="radio" /> 
     <input id="radio2" type="radio" /> 
     <input id="buttn1" type="submit" /> 
</form> 

그리고이 양식을 제출하려면 다음 스크립트를 사용하십시오.

var form = document.getElementById('form1'); 

for(var i = 0; i < form.elements.length; i++) { 
    var element = form.elements[i]; 
    if(element.id == 'radio2') { 
     element.setAttribute("checked", "checked");   
    } 
    if(element.id == 'buttn1') { 
     var button = element; 
    } 
} 
button.click(); 

나는 바로 거기에이 작업을 수행 할 가능성이 1,000 더 나은 방법이 있지만,이 상황에서 작동 동의 할 것이다. 그것은 완벽하게 작동하지만 난 좀 내가 입력 이미지 개체를 클릭()를 호출하여 같은 일을 시도했지만 그것이 작동하지 않는 것

<form id="form2"> 
    <input type="image" id="img1" src="img1.png" /> 
    <input type="image" id="img2" src="img2.png" /> 
</form> 

다음 양식을 제출에 붙어 있어요. 어떤 제안. jQuery를 사용하는 것은 좋지만 클린 JS 버전에 특히 관심이 있습니다.

+0

실제로 비슷한 질문을 발견했지만 그 대답은 존재하지 않는 리소스에 대한 링크였습니다. – TFennis

답변

1

각 이미지의 이름을 지정하고 jQuery를 사용하는 경우 $("#<image_id>").click();을 호출 해보십시오.

<form id="form2" method="get"> 
    <input type="image" id="img1" src="https://encrypted.google.com/images/logos/ssl_logo.png" name="image1"/> 
    <input type="image" id="img2" src="http://www.w3schools.com/images/w3schoolslogo.gif" name="image2"/> 
</form> 

서버는 여기 JQuery와 사용하는 것보다 가벼운 솔루션입니다 image1.x=0&image1.y=0 or image2.x=0&image2.y=0

+0

jquery없이 작동하지 않는 이유는 무엇입니까? – TFennis

+1

jQuery 없이도 작동합니다. 다음을 참조하십시오 : http://fiddle.jshell.net/diode/yqMW9/5/show. – Diode

0

당신은 아래에 대응 JQuery Submit

$('#Form2').submit(); 

를 사용할 수 있습니다, 이것은 단순히 형태와 모든 데이터를 제출합니다. Form1을 제출하고 대신 제출하십시오.

이것이 1.7에서 실패하는 이유가 분명하지 않습니다. 다른 자바 스크립트 코드가 있습니까?

+0

클릭 한 이미지를 식별하기 위해 서버가 필요로하는 x 및 y 좌표를 제출하지 않습니다! – TFennis

+0

사이드 노트 : jQuery 1.7.1을 포함하지만 1.3.2에서 작동하면이 작은 코드가 작동하지 않습니다. – TFennis

2

같은 매개 변수가 나타납니다

HTMLElement.prototype.click = function() { 
    var evt = this.ownerDocument.createEvent('MouseEvents'); 
    evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null); 
    this.dispatchEvent(evt); 
} 

그런 다음 그것을 활용하는 '클릭'

라는 이름의 새로운 프로토 타입을 추가하기 ..

<form> 
    <input id="some_id" type="checkbox" name="foo"></input> 
</form> 
<script> 
    document.getElementById('some_id').click(); 
</script> 
관련 문제