0

In a scenario like below how to get imgt in console:

function test(e){
let tg = e.target.attr('data-tg');
console.log(tg); // error - target is undefined
}

$('button').on('click', function(e){
let fn = $(this).attr('data-fn');
window[fn]();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button data-tg='imgt' data-fn='test'>CLICK</button>

2
  • By it's self, e.target is only an element and will not be able to have .attr() function. This should show in your Console. Suggest wrapping it, $(e.target).attr() to get proper result. Commented Jan 7, 2020 at 18:43
  • Also window[fn]() would be called with argument, shouldn't it? (window[fn](e)) Commented Jan 7, 2020 at 18:44

1 Answer 1

2

By it's self, e.target is only an element and will not be able to have .attr() function. This should show in your Console.

Also, you do not pass any arguments to the function. Consider the following.

function test(e) {
  if (e == undefined) {
    console.log("Event is Undefined");
    return false;
  }
  let tg = $(e.target).data('tg');
  console.log(tg); // error - target is undefined
}

$("#btn-1").on('click', function(event) {
  let fn = $(this).data('fn');
  window[fn](event);
});
$("#btn-2").on('click', function(event) {
  let fn = $(this).data('fn');
  window[fn]();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="btn-1" data-tg='imgt' data-fn='test'>Test 1</button><button id="btn-2" data-tg='imgt' data-fn='test'>Test 2</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.