[英]Get form id when button is clicked JavaScript
<div class = "card text-center" id = "{{i[0]}}div">
<div class = "card-text">
<p> {{i[3]}} / kg </p>
<form>
<input type = "number" min = 0 max = 100 id = "{{i[0]}}form" class = "form-control"
></input>
<button
class = "btn btn-primary" id = "{{i[0]}}btn" onclick = "addCart(this)"
>Add to cart</button>
</div>
</div>
</div>
</form>
我有這個 for 循環,它遍歷列表並為每次迭代創建一個表單 + 按鈕。
例子:
list ["Papaya", "Banana"]
然后代碼會有一個表單和按鈕,id 為“Papayaform/Bananaform”和“Papayabtn 和 Bananabtn”
現在我正在嘗試將表單值存儲到本地存儲中(我聽說這是來自 HTML5),我正在做的方法是獲取按鈕的parentNode
的 id(this)
function addCart(e) {
var x = e.parentNode.id
document.body.append(x)
}
我試圖附加父級的 id 只是為了驗證它是否獲得了正確的輸入,但沒有結果(無法使用 console.log,因為我在移動設備上編碼)
有沒有其他方法可以解決這個問題?
我試過了
<button onclick = "addCart(this.target.parentNode.id)">
this.target.parentNode.id
this.parentElement.id
首先,您的 Html 示例</form>
不正確, </form>
結束標記應直接在按鈕結束元素之后。 其次,在示例中,您沒有為表單元素提供 id 屬性(必須是<form id="myformid">
。我這樣做了,此 Javascript 將顯示表單元素的 id:
<script>
function addCart(btn) {
alert(btn.parentElement.id);
}
</script>
我會簡單地將它添加為按鈕上的data attribute
,然后使用getAttribute
檢索它。
遍歷 html 是有問題的,並且可能會因簡單的結構更改而中斷。
請參閱下面的片段,在您的情況下,它將是:
<button onclick="console.log(this.getAttribute('data-formId'))" data-formId="{{i[0]}}div">
Click me
</button>
<button onclick="console.log(this.getAttribute('data-formId'))" data-formId="10"> Click me to console log form Id which is 10 </button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.