![](/img/trans.png)
[英]How can I use javascript to “click” a button that has no id or name?
[英]How can i click a button with a custom ID that is not recognized in Javascript? If there is not a name or tag or ID, can it be done?
有一個網站我正在嘗試使用 JavaScript 自動應用折扣代碼。 我需要知道另一種方法來讓這個特定按鈕提交()或點擊()它。 我已經找到了一種輸入代碼的方法,因為該元素有一個 ID。 但是,此按鈕並非如此。 當我使用 data-trekkie-id ID“apply_discount_button”時,它無法識別該 ID。
<button name="button" type="submit" class="field__input-btn btn btn--disabled" data-trekkie-id="apply_discount_button" aria-busy="false">
<span class="btn__content visually-hidden-on-mobile" aria-hidden="true">
Apply
</span>
<span class="visually-hidden">
Apply Discount Code
</span>
<svg class="icon-svg icon-svg--size-16 btn__icon shown-on-mobile" aria-hidden="true" focusable="false"> <use xlink:href="#arrow" /> </svg>
<svg class="icon-svg icon-svg--size-18 btn__spinner icon-svg--spinner-button" aria-hidden="true" focusable="false"> <use xlink:href="#spinner-button" /> </svg>
我沒有得到 100% 的關於你正在尋找的東西。 但我猜您想選擇帶有自定義 html5 數據屬性( data-trekkie-id
)的按鈕。
您可以使用以下行在 javascript 中選擇按鈕:
const discountButton = document.querySelector('[data-trekkie-id="apply_discount_button"]');
它將返回具有屬性data-trekkie-id="apply_discount_button"
的第一個匹配項。
然后你可以通過附加addEventListener
方法來監聽這個元素上的事件。
就像你想監聽這個元素上的點擊事件一樣,代碼將是:
discountButton.addEventListener('click', function(){
alert('Discount button was clicked.'); // Replace this line with your code
});
由於 HTMl 的靈活性,您可以創建自己的屬性並隨心所欲地使用它們; 如果您曾經使用過引導程序,您會看到它們向 html 標簽添加了一些屬性,您也可以這樣做。 要使用 data-trekkie-id 屬性捕獲按鈕上的 clic 事件,您可以讓 Jquery 執行以下操作:
$("[data-trekkie-id=apply_discount_button]").click(function(){
//some stuff
})
或者干脆:
$("[data-trekkie-id]").click(function(){
//some stuff
})
希望我的回答有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.