简体   繁体   中英

How to pass data- value to jquery function

I have this HTML line with combination of TWIG code:

<a href="#" class="aaa" data-redirect="{{ path('rezervace_smazat', {'terminId':rezervaceTabulka[i]['id_rezervace']}) }}"> delete </a>

The line is a part of cycle, so in final result it can be multiple with different value of data-redirect attribute.

I need to pass the value of data-redirect to jquery function, but only a specific value when I click the hyper text link.

$(document).ready(function() {
        $('.aaa').on( "click", function(e) {
                e.preventDefault();
                $.confirm({
                        title: 'Smazat termín',
                        message: 'Opravdu chcete smazat tento termín?',
                        labelOk: 'Smazat',
                        labelCancel: 'Storno',
                        onOk: function() {
                                window.location.assign($(this).attr("data-redirect"));
                        }
                });
        });
});

The function works fine except of the line, where I need to redirect to different URL. I need to pass to the window.location.assign() function the specific value from data-redirect attribute.

Actually $(this).attr("data-redirect") does not pass the value from the attribute.

Thank you for help.

Try using. I hope this one helps.

$(this).data('redirect');

I believe is this is an issue. Sorry I just had to.

What I mean is

...
onOk: function() {
  window.location.assign($(this).attr("data-redirect"));
                           ^----- may not be referring to what you think it is.
}
...

A quick solution would be to change to to an arrow function like so

onOk: () => { window.location.assign($(this).attr("data-redirect")); }

If you need better support coverage you could assign the variable this as a work around like so

$(document).ready(function() {
        $('.aaa').on( "click", function(e) {
                var self = this; // <--- here 
                e.preventDefault();
                $.confirm({
                        title: 'Smazat termín',
                        message: 'Opravdu chcete smazat tento termín?',
                        labelOk: 'Smazat',
                        labelCancel: 'Storno',
                        onOk: function() {
                                window.location
                                      .assign($(self)
                                      .attr("data-redirect")); // <--- and here
                        }
                });
        });
});

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