[英]How to simulate an image-button click
I've been doing web development for quite some time but I only recently discovered the existence of the <input type="image">
tag. 我从事Web开发已经有一段时间了,但是最近才发现<input type="image">
标签的存在。
I have a greasemonkey script that automatically submits the following form on a webpage. 我有一个lublessmonkey脚本,可以在网页上自动提交以下表单。
<form id="form1">
<input id="radio1" type="radio" />
<input id="radio2" type="radio" />
<input id="buttn1" type="submit" />
</form>
And I use the following script to submit this 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();
I will immediately agree there are possibly 1000 better ways to do this but it works in this situation. 我将立即同意,可能有1000多种更好的方法可以做到这一点,但是在这种情况下它可以工作。 It works perfectly but I'm kinda stuck on submitting the following form 效果很好,但我有点坚持提交以下表格
<form id="form2">
<input type="image" id="img1" src="img1.png" />
<input type="image" id="img2" src="img2.png" />
</form>
I've tried doing the same by calling click() on the input-image object but that doesn't seem to work. 我试图通过在输入图像对象上调用click()来做同样的事情,但这似乎不起作用。 Any suggestions. 有什么建议么。 Using jQuery is fine but I'm particularly interested in the clean JS version. 使用jQuery很好,但是我对干净的JS版本特别感兴趣。
Here's a lighter solution than using jquery: 与使用jquery相比,这是一个更轻松的解决方案:
Add a new prototype named 'click' 添加一个名为“ click”的新原型
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);
}
Then to utilize it.. 然后利用它。
<form>
<input id="some_id" type="checkbox" name="foo"></input>
</form>
<script>
document.getElementById('some_id').click();
</script>
Give names for each image, and try calling $("#<image_id>").click();
为每个图像命名,然后尝试调用$("#<image_id>").click();
, if you are using jQuery. ,如果您使用的是jQuery。
<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>
Server will receive parameters like image1.x=0&image1.y=0 or image2.x=0&image2.y=0
服务器将接收像image1.x=0&image1.y=0 or image2.x=0&image2.y=0
You could use JQuery Submit 您可以使用JQuery Submit
$('#Form2').submit();
In response to below, this will simply submit the form and all the data. 作为对以下内容的回应,这将简单地提交表单和所有数据。 If you want to submit Form1 then submit that instead. 如果要提交Form1,请改为提交。
There is also no obvious reason why this would be failing in 1.7 - is there other Javascript code? 也没有明显的原因为什么在1.7中会失败-是否还有其他Javascript代码?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.