0

 $("#btn").on("click",()=>{
  var el = $(this);
 el.parent().find("#lbl").html("a");
 });
 
  $("#btn1").on("click",function(){
  var el = $(this);
 el.parent().find("#lbl").html("a"); 
 });
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvHeader">
<label id="lbl">Hello WOrld</label>
<button id="btn">
Button 1!
</button>
<button id="btn1">
Button 2!
</button>
</div>

I'm starting to learn an arrow function. I am wondering the two code above for button function don't work properly in an arrow function. But the other one is working properly. Did I do wrong?.

KiRa
  • 924
  • 3
  • 17
  • 42

3 Answers3

1

But if you want to use arrow functions in your jQuery event handlers you can use the event object inside your listener like this

$("#btn").on("click", e => $(e.target).parent().find("#lbl").html("a"));

$("#btn1").on("click", function() {
  $(this).parent().find("#lbl").html("a");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvHeader">
  <label id="lbl">Hello WOrld</label>
  <button id="btn">Button 1!</button>
  <button id="btn1">Button 2!</button>
</div>
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18
0

I have changed you code to achieve what you are trying to do: Demo

Also change your function to as below:

$("#btn").on("click",()=>{
  var el = document.getElementById("lbl");
  el.textContent = 'a';
 });
Pritesh
  • 337
  • 1
  • 10
0

Alternatively, you can use 「event.currentTarget」.
For example, below code works.

$("#btn").on("click", (event) => {
    var el = $(event.currentTarget);
    el.parent().find("#lbl").html("a");
});

<!DOCTYPE html>
<html>
<head>
    <title>test page</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <div id="dvHeader">
        <label id="lbl">Hello World</label>
        <button id="btn">
            Button 1!
        </button>
        <button id="btn1">
            Button 2!
        </button>
    </div>
    <script>
        $("#btn").on("click", (event) => {
            var el = $(event.currentTarget);
            el.parent().find("#lbl").html("a");
        });

        $("#btn1").on("click", function(){
            var el = $(this);
            el.parent().find("#lbl").html("a"); 
        });
    </script>
</body>
</html>