简体   繁体   中英

How to accept multiple class parameter in a function to create button in javascript

I'm new in javascript. I'm trying to create button like this.

<button class="btn btn-info fa fa-check"></button>

Here is my javascript function and it works

function createButton(buttonTypeClass, eventListener) {
    const button = document.createElement("button");
    button.classList.add(buttonTypeClass, "btn", "btn-info", "fa");
    button.addEventListener("click", function(event) {
        eventListener(event);
    });
    return button;
}

......

function createCheckButton() {
    return createButton("fa-check", function(event) {
        addBookToCompleted(event.target.parentElement);
    });
}

But what I want defining class of btn-info (from createButton function) inside createCheckButton function coz I wanna make another style button (eg createTrashButton with class btn-danger).

function createCheckButton() {
    return createButton("btn-info", "fa-check", function(event) {
        addBookToCompleted(event.target.parentElement);
    });
}

And it doesn't work well. It's only accept the first class (btn-info). How to fix this?

I would pass in an array of classes you want included on the button. This would be functionally correct.

function createButton(buttonTypeClasses, eventListener) {
    const button = document.createElement("button");
    buttonTypeClasses.forEach((class) => button.classList.add(class));
    button.classList.add("btn", "fa");
    button.addEventListener("click", function(event) {
        eventListener(event);
    });
    return button;
}

function createCheckButton() {
    return createButton(["btn-info", "fa-check"], function(event) {
        addBookToCompleted(event.target.parentElement);
    });
}

If you want to use the old function syntax, the forEach line would look like this.

buttonTypeClasses.forEach(function(class) { button.classList.add(class); });

It's probably because the function createButton() only accepts two params but instead you gave it three params. Try using two params for the class names and one more for the event like

createButton(btnClass, btnClass2, eventListener) {
    const button = document.createElement("button");
    // do your thing here
    return button;
}

Another solution would be using the arguments array to pass a variable number of params

createButton() {
    // arguments array contains all of the params you want to pass and its variable
    // do your thing here
    return button;
}

Here's an example I put together to explains arguments usage

function test() {
    console.log(arguments) // prints all of the values you passed to it
}
test(1, 2, 3, 4)

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