亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用JavaScript捕獲發生點擊事件時的p元素值

如何使用JavaScript捕獲發生點擊事件時的p元素值

千巷貓影 2023-07-20 17:21:51
這是我的代碼。我想在單擊按鈕時捕獲星云和價格 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.
查看完整描述

1 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

您可以使用this來引用單擊的按鈕,.parentElement向上爬,然后選擇段落及其內部文本。可以從那里按照您喜歡的方式解析文本。


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>


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號