从 Java 服务器加载 JSON ajax 后无法获取 h1 标记的内部 HTML

Can't get innerHTML of the h1 tag after JSON ajax load from Java Server

本文关键字:h1 获取 HTML 内部 服务器 Java 加载 JSON ajax      更新时间:2023-09-26
$.ajax({
  type: "GET",
  url: "/users",
  dataType: "json",
  success: function(people) {
    people.forEach(function(person) {
      usersDiv.innerHTML += '<div>'+
      '<h1>' + person.username + '</h1>'+
      '<button class="send-message">Write message</button>'+
      '</div>'; },
  error: function(err) {
    alert("blad + error" );
  },
  contentType: "application/json"
    }).done(function() {
      $(".send-message").click(function() {
        var that = $(this);
        var parentOfThat = that.parent();
        var nameOfTheUser = String(parentOfThat.find("h1").textContent); 
      });
    )

这段代码工作得很好。它用 h1 paragraf 填充 userDiv,其中包含来自 json 对象的每个人名。当我想检索 h1 innerHTML 的名称时,它会产生未定义。我尝试了几乎所有的方法,从text()到html()等等。

您可以尝试使用 find("h1").eq(0).text()

或 find("h1:first").text() 来确保只检索一个元素吗?

更改为此

contentType: "application/json"
    }).done(function() {
      $(".send-message").click(function() {
         var nameOfUser = $(this).prev('h1').text();
         //alert(nameOfUser);
      });
    )

下面是 JSFiddle 来展示此更改的工作原理

好的,问题解决了!我实际上在那里还有一个div!所以而不是

String(parentOfThat.find("h1").textContent)

我不得不将其更改为:

String(parentOfThat.parent().find("h1").textContent)