How to dynamically populate javascript function parameters

I have an application in which javascript and html are pretty much separate. I am trying to write something with javascript or jquery that will extract all the data attributes from the html element and put them in the parameters for the javascript function, dynamically. There are many options, every time this script is mentioned, not all will be used.

First an example, then poorly show how I do it (semi-successfully).

HTML:

<button data-behavior="sweetalert" data-title="Alert Title" data-text="Lorem ipsum dolar..." data-showCancelButton="true">Click Me</button>

JavaScript:

sweetAlert({
    title: "Alert Title",
    text: "Lorem ipsum dolar...",
    showCancelButton: true,
});

Straight right? Ok, now let's get some fantasy and populate it dynamically. So I want to be able to find the option in sweetAlert api, and then just connect it to the html element with data-attribute. This way, people with an interface can add fast html without script tags.

, , , , , (, ).

$('[data-behavior="sweetalert"]').click(function() {
    attributes = $(this).data();
    delete attributes["behavior"];
    sweetAlert($.each(attributes, function(key, value) {
        key + ": " + value + ', '
    }));
});

, . .

- , , ( ) ?

, - ... !

+4
1

jQuery .data() "true" true. :

$('[data-behavior="sweetalert"]').click(function() {
    attributes = $(this).data();
    delete attributes["behavior"];
    sweetAlert(attributes);
});

data() , .

, OP: . , data() showCancelButton, data-show-cancel-button .

+5

Source: https://habr.com/ru/post/1623822/


All Articles