![](/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.