简体   繁体   English

选择与其他元素具有相同 class 的特定元素的值

[英]Selecting the value of specific element with the same class as others

 <body> <div class = "element"> Monday - <button class= "delete_button">Delete</button> </div> <div class = "element"> Tuesday - <button class= "delete_button">Delete</button> </div> <div class = "element"> Wednesday - <button class= "delete_button">Delete</button> </div> </body>

For that HTML I have a JavaScript file with function with onclick event listener for class= "delete_button" and the goal is to get in JavaScript variable the value of the specific div in which is the button that has been pressed. For that HTML I have a JavaScript file with function with onclick event listener for class= "delete_button" and the goal is to get in JavaScript variable the value of the specific div in which is the button that has been pressed.

With the JS function parentElement and split you can do it as well.使用 JS function parentElement 和 split 你也可以做到这一点。

 function deleteThis (e) { const v = e.parentElement.innerText.split('-') console.log('The value from div is: ', v[0]) alert(v[0]) }
 <body> <div class = "element"> Monday - <button class= "delete_button" onclick="deleteThis(this)">Delete</button> </div> <div class = "element"> Tuesday - <button onclick="deleteThis(this)" class= "delete_button">Delete</button> </div> <div class = "element"> Wednesday - <button onclick="deleteThis(this)" class= "delete_button">Delete</button> </div> </body>

small note Try to avoid to use the onclick element.小记尽量避免使用 onclick 元件。 Better to bind the buttons to a EventListener..最好将按钮绑定到 EventListener..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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