jQuery .on() click event catching dynamic 'dat

2020-06-01 07: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 a common class which needs to access the value of a data- attribute within the button image code seen further below:

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

Example of the edit buttons which are dynamically generated:

<img src="edit.png" title="edit" class="showEdt" data-evalz="(eyCKeVua/TNF117)" />

Problem:

The script loads ok, when the edit button is clicked the alert displays: [object HTMLImageElement] instead of the data-evalz value ??

Please provide suggestions of how I can access the data unique to the button that is clicked?

5条回答
ゆ 、 Hurt°
2楼-- · 2020-06-01 08:09

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...

查看更多
狗以群分
3楼-- · 2020-06-01 08:20

or just from the event

event.target.attributes.qelemnumber.value
查看更多
冷血范
4楼-- · 2020-06-01 08:27

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.

查看更多
啃猪蹄的小仙女
5楼-- · 2020-06-01 08:30

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...
});
查看更多
女痞
6楼-- · 2020-06-01 08:33
$("body").on("click",".showEdt",function(){
    alert($(this).attr("data-evalz"));
});

Fiddle here.

查看更多
登录 后发表回答