如何获取document选择器点击元素的值及在addTab函数中传递label的ID/值
Hey there! Let's tackle your two questions one by one with clear, practical examples:
When you bind a click event to an element, the event callback receives an event parameter. The event.target property in this parameter points directly to the element that was clicked. You can extract different values from it based on your needs:
- To get the element's ID: Use
event.target.id - To get the text content inside the element (like your label's displayed text): Use
event.target.textContentorevent.target.innerText - To get custom data attributes (like your
data-add-tab): Useevent.target.dataset.addTab(note that dataset converts kebab-case attributes to camelCase automatically) - For input elements, to retrieve their user-input value: Use
event.target.value
Here's a quick demo using your label element:
document.querySelector('label[data-add-tab]').addEventListener('click', (event) => { const clickedElement = event.target; console.log('Clicked element ID:', clickedElement.id); console.log('Clicked element text:', clickedElement.textContent); });
You can pass the label's ID or text to the addTab function by first grabbing the clicked label via event.target, then including those values in the configuration object you send to addTab.
Here's how to adjust your existing code:
<label data-add-tab id="my_IdValue">my_IdValue</label> <script> var newTabs = new NewTabs() document.querySelector('label[data-add-tab]').addEventListener('click', (event) => { // Capture the clicked label element const clickedLabel = event.target; // Pass the label's ID and text to the addTab method newTabs.addTab({ title: clickedLabel.textContent, // Use the label's text as the new tab's title favicon: false, sourceLabelId: clickedLabel.id // Custom property to carry the label's ID }) }) </script>
Then, inside your NewTabs class's addTab method, you can access these values from the options object:
class NewTabs { addTab(options) { // Access the passed label ID and text here console.log('Source label ID:', options.sourceLabelId); console.log('Tab title from label text:', options.title); // Your existing tab creation logic goes here... } }
内容的提问来源于stack exchange,提问作者Yaseer Hussain

