![](/img/trans.png)
[英]How to get the ID of the html element which is calling the function? (Jquery/Javascript)
[英]How to get html of element with arrow function with jquery
我們使用的語法需要使用箭頭函數。 我仍在學習我們的軟件,所以我無法回答為什么。 問題是我不知道如何將 function() { }callbacks 轉換為 (e) => callbacks 並且我嘗試過的解決方案不起作用。
我已閱讀有關 .each()、.find()、.html() 和 $(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
按預期運行,但withArrow
沒有
預期結果:這兩個函數都改變了 html 的
新內容的標簽。 記錄 html 標記內容時,兩個函數都應打印到控制台。
實際:只有第一個 function 改變了
標簽。 第一個 function 將正確的值打印到控制台,但第二個 function 打印未定義。
箭頭function沒有錯。
您只是以錯誤的方式使用each() function。 您需要使用該value
來獲取元素。 正常 function 沒有這個問題,因為您使用的是this
而不是回調參數。
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
更正的片段
// 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.