猿问

如何使用JavaScript捕获发生点击事件时的p元素值

这是我的代码。我想在单击按钮时捕获星云和价格 1.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>

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.


千巷猫影
浏览 100回答 1
1回答

临摹微笑

您可以使用this来引用单击的按钮,.parentElement向上爬,然后选择段落及其内部文本。可以从那里按照您喜欢的方式解析文本。var calHosting = document.querySelectorAll('.calculate-hosting');[...calHosting].forEach(cal => {&nbsp; &nbsp; cal.addEventListener('click', function (event) {&nbsp; &nbsp; &nbsp; &nbsp; var paragraphs = this.parentElement.querySelectorAll("p");&nbsp; &nbsp; &nbsp; &nbsp; var p1 = paragraphs[0].innerText;&nbsp; &nbsp; &nbsp; &nbsp; var p2 = paragraphs[1].innerText;&nbsp; &nbsp; &nbsp; &nbsp; var price = Number(p2.match(/\d+\.\d+/)[0]);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; console.log(p1); // Nebula&nbsp; &nbsp; &nbsp; &nbsp; console.log(p2); // Price1.44 /mo&nbsp; &nbsp; &nbsp; &nbsp; console.log(price); // 1.44&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // document.getElementById('cal-container').style.display = 'block';&nbsp; &nbsp; });});<div class="item__top">&nbsp; &nbsp; <p> Nebula</p>&nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; Price<span class="big-price">1</span>.44&nbsp; &nbsp; &nbsp; &nbsp; <span class="text-large">/mo</span>&nbsp; &nbsp; </p>&nbsp; &nbsp; <p>$2.88</p>&nbsp; &nbsp; <button class="calculate-hosting">Get Started</button>&nbsp; &nbsp; <p>You pay $17.28 — Renews at $33.88/year</p></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答