jQuery .on() click event catching dynamic 'data-' attribute in list of buttons to pass value to other function?

前端 未结 5 1188
误落风尘
误落风尘 2021-02-07 04:57

I have a dynamic table list of around 40 rows each with an edit button containing a date field. I also have the following click event script trying to attach to each button via

相关标签:
5条回答
  • 2021-02-07 05:08
    $("body").on("click",".showEdt",function(){
        alert($(this).attr("data-evalz"));
    });
    

    Fiddle here.

    0 讨论(0)
  • 2021-02-07 05:10

    You're not using the on function correctly. Here's one way you can do this: FIDDLE

    $('.showEdt').each(function () {
        var $this = $(this);
        $this.on("click", function () {
            alert($(this).data('evalz'));
        });
    });
    

    Also, notice you've written eValz instead of evalz on your code. Data attributes are case-sensitive so be careful with how you write them.

    0 讨论(0)
  • 2021-02-07 05:13

    If you're changing the context of 'this' keyword to something else, you can retrieve the data directly from the 'event' object like so:

    $('element').on('click', function(event) {
        // 'this' here = externalObject
        this.fnFromExternalObject($(event.currentTarget).data('activate'));
    }.bind(externalObject));
    

    I hope the example above is clear...

    0 讨论(0)
  • 2021-02-07 05:14

    If your data attribute is known, you can do it directly with an attribute selector in jQuery, like this:

    $(document).on('click', "[data-attribute]", function() {
        // Do your tricks here...
    });
    
    0 讨论(0)
  • 2021-02-07 05:22

    or just from the event

    event.target.attributes.qelemnumber.value
    
    0 讨论(0)
提交回复
热议问题