首页 > 解决方案 > 如何使用jquery获取带有箭头功能的元素的html

问题描述

我们使用的语法需要使用箭头函数。我仍在学习我们的软件,所以我无法回答为什么。问题是我不知道如何将 function() { }callbacks 转换为 (e) => callbacks 并且我尝试过的解决方案不起作用。

我已阅读有关 .each()、.find()、.html() 和 $(this) 与 $(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 标记内容时,两个函数都应打印到控制台。

实际:只有第一个函数改变了

标签。第一个函数将正确的值打印到控制台,但第二个函数打印未定义。

标签: javascriptjquery

解决方案


箭头功能没有任何问题。

您只是以错误的方式使用each()函数。您需要使用value来获取元素。普通函数在您使用时没有这个问题,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>


推荐阅读