[英]how to capture p elements value when click event happened using JavaScript
Here is my code.这是我的代码。 I want to capture Nebula and Price 1.44 when I click on button.
我想在单击按钮时捕获星云和价格 1.44。 Can anyone help me please.
任何人都可以请帮助我。
Html code html代码
<div class="item__top">
<p> Nebula</p>
<p>
Price<span class="big-price">1</span>.44
<span class="text-large">/mo</span>
</p>
<p>$2.88</p>
<button class="calculate-hosting">Get Started</button>
<p>You pay $17.28 — Renews at $33.88/year</p>
</div>
JS code JS代码
var calHosting = document.querySelectorAll('.calculate-hosting');
[...calHosting].forEach(cal=>{
cal.addEventListener('click',function(event){
document.getElementById('cal-container').style.display='block';
});
});
Note: I am dealing with mutiple buttons so thats why I sued querySelectorAll.
You can use this
to refer to the button that was clicked, .parentElement
to climb up, and then select paragraphs and their inner text.您可以使用
this
来引用被单击的按钮, .parentElement
向上爬,然后选择段落及其内部文本。 The text can be parsed however you like from there.可以根据需要从那里解析文本。
var calHosting = document.querySelectorAll('.calculate-hosting'); [...calHosting].forEach(cal => { cal.addEventListener('click', function (event) { var paragraphs = this.parentElement.querySelectorAll("p"); var p1 = paragraphs[0].innerText; var p2 = paragraphs[1].innerText; var price = Number(p2.match(/\\d+\\.\\d+/)[0]); console.log(p1); // Nebula console.log(p2); // Price1.44 /mo console.log(price); // 1.44 // document.getElementById('cal-container').style.display = 'block'; }); });
<div class="item__top"> <p> Nebula</p> <p> Price<span class="big-price">1</span>.44 <span class="text-large">/mo</span> </p> <p>$2.88</p> <button class="calculate-hosting">Get Started</button> <p>You pay $17.28 — Renews at $33.88/year</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.