简体   繁体   中英

I have a dynamic html template. Which forms when I click on a button. Now, the problem is When I click on one button all buttons are clicked

Here is the html template forms when I click on a button.

<div class="detail">
                    <h3>${element.name}</h3>
                    <p>Phone: ${element.phone}</p>
                    <button onclick="addToHistory()">Call</button>
                </div>`

Let's say it creates two template as it is.

<div class="detail">
                        <h3>Person1</h3>
                        <p>Phone: 0111111111</p>
                        <button onclick="addToHistory()">Call</button>
                    </div>`

<div class="detail">
                        <h3>Person2</h3>
                        <p>Phone: 0111111111</p>
                        <button onclick="addToHistory()">Call</button>
                    </div>`

Now, I want to click on one button and then according to my click I want the data of clicked divs should store.

I tried this using event handler as you can see with addToHistory() function. But, it stores all the data both I clicked and not clicked also.

Please note: I want to do this only using JavaScript. Thank you for your support.

You can pass this into your method and use that to traverse within the specific detail container where the button was clicked.

this will reference the specific element the event occurs on

 function addToHistory(el){ console.log(el.previousElementSibling.textContent); }
 <div class="detail"> <h3>Person1</h3> <p>Phone: 0999999999</p> <button onclick="addToHistory(this)">Call</button> </div>` <div class="detail"> <h3>Person2</h3> <p>Phone: 0111111111</p> <button onclick="addToHistory(this)">Call</button> </div>`

We can trigger button click by class. 
Please check this example `https://jsfiddle.net/h54dt731/`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM