简体   繁体   中英

How to get html of element with arrow function with jquery

The syntax we are using requires the use of arrow functions. I'm still learning our software so I couldn't answer as to why. The issue is I do not know how to convert function() { }callbacks to (e) => callbacks and the solutions I have tried are not working.

I have read all the documentation and other answers regarding.each(), .find(), .html(), and $(this) vs $(e.currentTarget)

JsFiddle: https://jsfiddle.net/4gvowa18/2/

var i = 0;
var withThis = $(document).find("p").each(function(){
  $(this).html(i++);
  console.log($(this).html());
});

var j = 10;
var withArrow = $(document).find("p").each((e) =>{
    $(e.currentTarget).html(j++);
    console.log($(e.currentTarget).html());
});

withThis runs as expected but withArrow does not

Expected results: Both functions change the html of the

tags to the new content. When logging the html tag content both functions should print to the console.

Actual: Only the first function changes the contents of the

tag. The first function prints the correct values to the console but the second function prints undefined.

There is nothing wrong with the arrow function.

You are just using the each() function the wrong way. You need to use the value to get the element. Normal function does not have this issue as you are using this and not the callback params.

$.each([ 52, 97 ], function( index, value ) {
  alert( index + ": " + value );
});

Corrected Snippet

 // find elements var banner = $("#banner-message") var button = $("button") var i = 0; $(document).find("p").each(function() { $(this).html(i++); //console.log($(this).html()); }); var j = 10; $(document).find("p").each((i, e) => { $(e).html(j++); //console.log($(e).html()); }); // handle click and add class button.on("click", function() { banner.addClass("alt") withArrow(); })
 body { background: #20262E; padding: 20px; font-family: Helvetica; } #banner-message { background: #fff; border-radius: 4px; padding: 20px; font-size: 25px; text-align: center; transition: all 0.2s; margin: 0 auto; width: 300px; } button { background: #0084ff; border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; color: #fff; } #banner-message.alt { background: #0084ff; color: #fff; margin-top: 40px; width: 200px; } #banner-message.alt button { background: #fff; color: #000; }
 <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <div id="banner-message"> <p>TEST</p> <p>Hello World</p> <p>Hello World</p> <p>Hello World</p> <p>Hello World</p> <p>Hello World</p> <button>Change color</button> </div>

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