如何将(新类)作为参数传递给按钮组件,而无需触发单击事件而执行函数。
class cDevice {
new() {
//something here;
}
}
device: {
// the (new cDevice).new() is what I want to pass.
createNew: function () { (new cDevice).new() },
}
这个参数将用于,当按钮点击事件被触发时执行(new cDevice).new()。
"<button onclick=" + device.createNew + ">new</button>"
谢谢!
为此,您必须在“onclick”事件上传递函数引用,而不是此时实际调用该函数。如果直接调用device.createNew()函数,则表示页面加载时会执行..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Button Click Example</title>
</head>
<body>
<script>
// Define cDevice class
class cDevice {
// The 'new' method inside cDevice class, logs when called
new() {
console.log('New device created'); // Log a message when a new device is created
}
}
// Define device object with method to create new device
const device = {
createNew: function() {
// This creates a new cDevice instance and calls its 'new' method
new cDevice().new(); // Calls the 'new()' method of the new device instance
}
};
// The function that gets triggered when the button is clicked
function handleClick() {
// When the button is clicked, this calls the 'createNew' method of device object
device.createNew(); // This calls device.createNew(), which creates a new cDevice and calls its 'new()'
}
// Wait until the HTML page is fully loaded before attaching the click event
document.addEventListener('DOMContentLoaded', function() {
// Find the button with id 'myButton' in the HTML
const button = document.querySelector('#myButton');
// Attach an event listener to the button for the 'click' event
button.addEventListener('click', handleClick); // When button is clicked, call 'handleClick' function
});
</script>
<!-- This is the button that will trigger the event -->
<button id="myButton">Create New Device</button>
</body>
</html>
我只是推迟了创建新设备的执行,直到单击按钮。如果我直接使用 onclick 事件调用 device.createNew() ,它会在网页加载完成后立即运行。所以,我让它只在用户单击按钮时运行。