[英]How do I use javascript to click a button with no on click event?
如何使用JavaScript單擊沒有ID的按鈕? 通常,我會做類似的事情:
document.getElementById("button").click();
這是HTML:
<form accept-charset="UTF-8" action="https://example.com/account/login" id="customer_login" method="post"><input name="form_type" type="hidden" value="customer_login" />
<input name="utf8" type="hidden" value="✓" />
<label for="customer_email" class="label">Email Address</label>
<input type="email" value="" name="customer[email]" id="customer_email" class="text" />
<label for="customer_password" class="label">Password</label>
<input type="password" value="" name="customer[password]" id="customer_password" class="text" size="16" />
<div class="action_bottom">
<input class="btn" type="submit" value="Sign In" />
<span class="note">or <a href="http://example.com">Return to Store</a></span>
</div>
</form>
我可以這樣填寫電子郵件和密碼框:
document.getElementById("customer_email").value = "myemail@mail.com";
document.getElementById("customer_password").value = "passwordtoenter";
您可以使用getElementsByClassName方法按類查找元素。 此方法返回類似數組的列表,因此您需要確切知道要單擊的按鈕。 假設只有一個按鈕具有“ btn”類,或者如果此按鈕在文檔流中排在首位,則可以執行以下操作:
document.getElementsByClassName("btn")[0].click();
我個人將使用jQuery完成此任務。 如今,使用純JavaScript似乎比實際更時髦。 例如:
$('#customer_email').val("myemail@mail.com");
$('#customer_password").val("passwordtoenter");
$('#customer_login .btn').click();
jQuery中的選擇器使JS的生活變得更加輕松。 我不確定讓javascript調用點擊而不是讓表單自己提交的目的是什么。 如果要執行一些自定義提交邏輯,則可以使用:
$("#customer_login .btn').on('click', function(e) {
//if you need to prevent the click events default action
e.preventDefault();
//Custom logic here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.