如何使用JavaScript捕获单击事件发生时的p元素值
这是我的密码。我想捕捉星云,当我点击按钮时,价格为1.44。谁能帮帮我吗 Html代码如何使用JavaScript捕获单击事件发生时的p元素值,javascript,Javascript,这是我的密码。我想捕捉星云,当我点击按钮时,价格为1.44。谁能帮帮我吗 Html代码 <div class="item__top"> <p> Nebula</p> <p> Price<span class="big-price">1</span>.44
<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>
您可以使用
this
引用单击的按钮,.parentElement
向上爬升,然后选择段落及其内部文本。文本可以从那里按您喜欢的方式进行解析
var calHosting=document.querySelectorAll('.calculate hosting');
[…calHosting].forEach(cal=>{
cal.addEventListener('click',函数(事件){
var段落=this.parentElement.querySelectorAll(“p”);
var p1=段落[0]。innerText;
var p2=段落[1]。内部文本;
var价格=数字(p2.匹配(/\d+\.\d+/)[0]);
console.log(p1);//星云
console.log(p2);//价格1.44/mo
console.log(price);/1.44
//document.getElementById('cal-container').style.display='block';
});
});代码>
星云
价格1.44
/钼
2.88美元
开始
您支付17.28美元-续费为33.88美元/年
是。我只想打印星云和1.44。
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.